在這里,我們將學(xué)習(xí)創(chuàng)建第一個(gè)spring應(yīng)用程序的簡(jiǎn)單步驟。要運(yùn)行此應(yīng)用程序,我們不使用任何IDE。我們只是在使用命令提示符。讓我們看看創(chuàng)建spring應(yīng)用程序的簡(jiǎn)單步驟
創(chuàng)建Java類(lèi) 創(chuàng)建xml文件以提供值 創(chuàng)建測(cè)試類(lèi) 加載spring jar文件 運(yùn)行測(cè)試類(lèi)
讓我們看一下創(chuàng)建第一個(gè)spring的5個(gè)步驟
這是僅包含name屬性的簡(jiǎn)單Java bean類(lèi)。
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類(lèi),僅包含一個(gè)帶有其getter和setters方法的屬性名稱(chēng)。此類(lèi)包含一個(gè)名為displayInfo()的附加方法,該方法通過(guò)問(wèn)候消息打印學(xué)生姓名。
如果使用myeclipse IDE, ,您無(wú)需創(chuàng)建xml文件,因?yàn)閙yeclipse可以自己完成此操作。打開(kāi)applicationContext.xml文件,并編寫(xiě)以下代碼:
<?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 元素用于為給定類(lèi)定義bean。 bean的 property 子元素指定名為name的Student類(lèi)的屬性。屬性元素中指定的值將由IOC容器在Student類(lèi)對(duì)象中設(shè)置。
創(chuàng)建Java類(lèi),例如測(cè)試。在這里,我們使用BeanFactory的getBean()方法從IOC容器中獲取Student類(lèi)的對(duì)象。讓我們看一下測(cè)試類(lèi)的代碼。
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(); } }
資源對(duì)象表示applicationContext.xml文件的信息。 Resource是接口,而 ClassPathResource 是Reource接口的實(shí)現(xiàn)類(lèi)。 BeanFactory 負(fù)責(zé)返回Bean。 XmlBeanFactory 是BeanFactory的實(shí)現(xiàn)類(lèi)。 BeanFactory接口中有很多方法。一種方法是 getBean(),該方法返回關(guān)聯(lián)類(lèi)的對(duì)象。
運(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文件,包括core,web,aop,mvc,j2ee,remoting,oxm,jdbc,orm等。
要運(yùn)行此示例,您只需要加載spring core jar文件。
現(xiàn)在運(yùn)行Test類(lèi)。您將得到輸出Hello: Vimal Jaiswal。