在這里,我們將使用eclipse IDE創(chuàng)建一個(gè)spring框架的簡(jiǎn)單應(yīng)用程序。讓我們看看在Eclipse IDE中創(chuàng)建spring應(yīng)用程序的簡(jiǎn)單步驟。
創(chuàng)建Java項(xiàng)目 添加spring jar文件 創(chuàng)建類 創(chuàng)建xml文件以提供值 創(chuàng)建測(cè)試類
讓我們看一下使用以下步驟創(chuàng)建第一個(gè)spring應(yīng)用程序的5個(gè)步驟: eclipse IDE。
轉(zhuǎn)到 文件菜單- 新建- 項(xiàng)目- Java項(xiàng)目。輸入項(xiàng)目名稱,例如firstspring- 完成?,F(xiàn)在,創(chuàng)建了Java項(xiàng)目。
運(yùn)行該應(yīng)用程序主要需要三個(gè)jar文件。
org.springframework.core-3.0.1.RELEASE-A com.springsource.org.apache.commons.logging-1.1.1 org.springframework.beans-3.0.1.RELEASE-A
為了將來(lái)使用,您可以下載spring核心應(yīng)用程序所需的jar文件。
下載Spring的核心jar文件
全部下載Spring的jar文件,包括aop,mvc,j2ee,remoting,oxm等。
要運(yùn)行此示例,您只需加載spring核心jar文件。
要在Eclipse IDE中加載jar文件, 右鍵單擊您的項(xiàng)目- 構(gòu)建路徑- 添加外部檔案文件- 選擇所有必需的文件jar文件- 完成。。
在這種情況下,我們只是在創(chuàng)建具有name屬性的Student類。學(xué)生的姓名將由xml文件提供。這只是一個(gè)簡(jiǎn)單的示例,而不是spring的實(shí)際使用。我們將在"依賴注入"一章中看到實(shí)際的用法。要?jiǎng)?chuàng)建Java類,請(qǐng) 右鍵單擊src - 新建- 類- 寫類名稱,例如學(xué)生- 完成。編寫以下代碼:
package com.nhooo; public class Student { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void displayInfo(){ System.out.println("Hello: "+name); } }
這是簡(jiǎn)單的bean類,僅包含一個(gè)帶有其getter和setters方法的屬性名稱。此類包含一個(gè)名為displayInfo()的附加方法,該方法通過(guò)問(wèn)候消息打印學(xué)生姓名。
創(chuàng)建xml文件單擊src-新建-file-給出文件名,例如applicationContext.xml-完成。打開applicationContext.xml文件,并編寫以下代碼:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="studentbean" class="com.nhooo.Student"> <property name="name" value="Vimal Jaiswal"></property> </bean> </beans>
bean 元素用于為給定類定義bean。 bean的 property 子元素指定名為name的Student類的屬性。屬性元素中指定的值將由IOC容器在Student類對(duì)象中設(shè)置。
創(chuàng)建Java類,例如測(cè)試。在這里,我們使用BeanFactory的getBean()方法從IOC容器中獲取Student類的對(duì)象。讓我們看一下測(cè)試類的代碼。
package com.nhooo; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Test { public static void main(String[] args) { Resource resource=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(resource); Student student=(Student)factory.getBean("studentbean"); student.displayInfo(); } }
現(xiàn)在運(yùn)行此類。您將得到輸出Hello: Vimal Jaiswal。