1、开发工具 Eclipse3.7 ,JDK 1.6.0_24 ;
具体步骤及源码如下:
1、新建一个Java project ,名字为 :springDemo1 ;
2、spring-framework-2.5.6.zip 解压,把其中...\spring-framework-2.5.6\dist\modules\spring-beans.jar 、...\spring-framework-2.5.6\dist\modules\spring-core.jar 和
...\spring-framework-2.5.6\lib\jakarta-commons\commons-logging.jar 复制出来放到 ...\workspace\spring-lib目录中 ;
3、选中第一步中新建的springDemo1 ,右键->Build Path->Configure Build Path... ; 在 Java Build Path窗口中选中Libraries,通过Add External JARs ,把第二步中的jar添加
到工程中 ;
4、新建一个接口 :GreetingService.java ,内容如下 :
package com.ex;
public interface GreetingService {
public void sayGreeting();
}
5、创建GreetingService的实现类 :GreetingServiceImpl.java ,内容如下:
package com.ex.impl;
import com.ex.GreetingService;
public class GreetingServiceImpl implements GreetingService{
private String greeting ;
public void setGreeting(String greeting) {
this.greeting = greeting;
}
public GreetingServiceImpl(){
}
public GreetingServiceImpl(String greeting){
this.greeting = greeting ;
}
@Override
public void sayGreeting() {
System.out.println(this.greeting) ;
}
}
6、在src下面创建配置文件 beans-config.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/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="greetingBean" class="com.ex.impl.GreetingServiceImpl">
<!-- //通过属性的setter方法设置属性值
<property name="greeting">
<value>Hello!Mr. Cai .</value>
</property>
-->
<!-- 通过带参数的构造方法设置属性值-->
<constructor-arg>
<value>Hello!Mr. cai dm .</value>
</constructor-arg>
</bean>
</beans>
7、新建测试类SpringDemo1.java 代码如下:
package com.ex.test;
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;
import com.ex.GreetingService;
public class SpringDemo1 {
/**
* @param args
*/
public static void main(String[] args) {
Resource rs = new ClassPathResource("beans-config.xml");
BeanFactory factory = new XmlBeanFactory( rs ) ;
GreetingService gs = (GreetingService)factory.getBean("greetingBean" ) ;
gs.sayGreeting() ;
}
}
运行结果:
2011-7-4 12:15:33 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-config.xml]
Hello!Mr. cai dm .