一、開發前的准備
兩個開發包spring-framework-3.1.1.RELEASE-with-docs.zip和commons-logging-1.2-bin.zip,將它們解壓,然后把Spring開發包下dist目錄的所有包和commons-logging包下的commons-logging-1.1.1.jar復制到名為Spring3.1.1的文件夾下。那么Spring開發所需要的包就組織好了。
二、建立項目,導入包
在項目節點上右鍵,Build Path/ADD Libraries/USER Libraries/new/輸入包名Spring3.1.1/OK/ADD JARS/選中准備好的包/OK。此外引入JUnit4方便程序測試。
三、添加文件
person接口Person.Java:
package com.bean; public interface Person{ public void Speak(); }
AmericanImpl.java:
package com.bean; public class AmericanImpl implements Person{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public void Speak() { // TODO Auto-generated method stub System.out.println("I'm American,My name is "+this.name+",I'm "+this.age+" years old!"); } }
ChineseImpl.java:
package com.bean; public class ChineseImpl implements Person{ private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public void Speak() { // TODO Auto-generated method stub System.out.println("I'm Chinese,My name is "+this.name+",I'm "+this.age+" years old!"); } }
配置文件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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean id="chinese" class="com.bean.ChineseImpl"> <property name="name"> <value>小明</value> </property> <property name="age"> <value>10</value> </property> </bean> <bean id="american" class="com.bean.AmericanImpl"> <property name="name"> <value>Tom</value> </property> <property name="age"> <value>15</value> </property> </bean> </beans>
用於測試的Test.java:
package com.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bean.Person; public class Test { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); Person person=(Person)context.getBean("chinese"); person.Speak(); person=(Person)context.getBean("american"); person.Speak(); } }
四、測試結果
在Test.Java上右擊Run As|Java Application,輸出結果如下: