首先是一个名叫Action的接口定义了一个execute()方法
package net.xiaxin.spring.qs;
public interface Action {
public String execute(String str);
}
实现类LowerAction
package net.xiaxin.spring.qs;
public class LowerAction implements Action {
private String message;
@Override
public String execute(String str) {
// TODO Auto-generated method stub
return (getMessage()+str).toLowerCase();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
实现类UpperAction
package net.xiaxin.spring.qs;
public class UpperAction implements Action {
private String message;
@Override
public String execute(String str) {
// TODO Auto-generated method stub
return (getMessage()+str).toUpperCase();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
新建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/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="TheAction" class="net.xiaxin.spring.qs.UpperAction">
<property name="message"><!--初始化-->
<value>HeLLo</value>
</property>
</bean>
</beans>
请确保配置bean.xml位于工作路径之下,注意工作路径并不等同于CLASSPATH ,eclipse的默认工作路径为项目根路径,也就是.project文件所在的目录,而默认输出目录/bin是项目CLASSPATH的一部分,并非工作路径。
测试类Test
package test;
import net.xiaxin.spring.qs.Action;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext txt=new FileSystemXmlApplicationContext("bean.xml");
Action action=(Action) txt.getBean("TheAction");
System.out.println(action.execute("sdf"));
}
}
上面的测试代码中,我们根据 "bean.xml" 创建了一个 ApplicationContext 实例,并从此实例中获取我们所需的Action实现
仔细观察一下上面的代码,可以看到:
1. 我们的所有程序代码中(除测试代码之外) ,并没有出现Spring中的任何组件。
2. UpperAction和LowerAction的Message属性均由Spring通过读取配置文件(bean.xml)动态设置。
3. 客户代码(这里就是我们的测试代码)仅仅面向接口编程,而无需知道实现类的具体名称。同时,我们可以很简单的通过修改配置文件来切换具体的底层实现类。
上面所说的这些,对于我们的实际开发有何帮助?
首先,我们的组件并不需要实现框架指定的接口,因此可以轻松的将组件从Spring中脱离,甚至不需要任何修改(这在基于EJB框架实现的应用中是难以想象的) 。
其次,组件间的依赖关系减少,极大改善了代码的可重用性。Spring的依赖注入机制,可以在运行期为组件配置所需资源,而无需在编写组件代码时就加以
指定,从而在相当程度上降低了组件之间的耦合。
上面的例子中,我们通过Spring,在运行期动态将字符串 “HeLLo” 注入到Action实现类的
以上例子来源于spring开发指南