注:简单演示了Spring最简单的用法。用于自己学习记录。
1、准备:
(1)最新版本Eclipse,http://www.eclipse.org/downloads/
(2)Spring插件:Latest GA release: 3.0.5.RELEASE http://www.springsource.org/download
包含:spring-framework-3.0.5.RELEASE-with-docs.zip 和spring-framework-3.0.5.RELEASE-dependencies
2、在Eclipse中新建一个 Java Project,命名为HelloSpring;
3、新建一个类:Flower.java
package wuyechun.hellosrping.spring;
public class Flower {
private int number;
private String name = "rose";
private String color = "red";
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
4、New —>Other—>Spring—>Spring Bean Configuration File 新建配置文件,命名为:bean.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" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="flower" class="wuyechun.hellosrping.spring.Flower"></bean> </beans>
5、将spring-framework-3.0.5.RELEASE\dist目录下的
org.springframework.asm-3.0.5.RELEASE.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.context-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar
org.springframework.expression-3.0.5.RELEASE.jar
放入到src目录下;
6、将spring-framework-3.0.5.RELEASE-dependencies\org.apache.commons\com.springsource.org.apache.commons.logging\1.1.1 目录下的
com.springsource.org.apache.commons.logging-1.1.1.jar
放入到src目录下;
注:将上面6个jar放到bulid path中。右键—>Build Path—>Add to Build Path
7、新建一个类:ShowFlower.java
package wuyechun.hellosrping.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class ShowFlower {
/**
* @param args
*/
public static void main(String[] args) {
// BeanFactory factory=new ClassPathXmlApplicationContext("beans.xml");
// Flower factory=context.getBean("flower",Flower.class);
ApplicationContext context=new FileSystemXmlApplicationContext("src/bean.xml");
Flower flower=context.getBean("flower",Flower.class);
System.out.println("Name:"+flower.getName()+" "+"Color:"+flower.getColor());
}
}