设值注入是指IOC容器使用属性的setter方法来注入被依赖的实例。这种注入方式简单,直观,因而在Spring的依赖注入里大量使用。
Spring推荐面向接口编程,这样可以更好地让规范和实现分离,从而提供更好的解耦。对于一个JavaEE应用,不管是DAO组件,还是业务逻辑组件,都应该先定义一个接口,该接口定义了该组件应该实现的功能,但功能的实现则由其实现类提供。
Person.java :
public interface Person {
public void useAxe();
}
Axe.java :
public interface Axe {
public String chop();
}
Chinese.java :public class Chinese implements Person {
private Axe axe;
public void setAxe(Axe axe) {
this.axe = axe;
}
@Override
public void useAxe() {
System.out.println(axe.chop());
}
}
StoneAxe.java :public class StoneAxe implements Axe {
@Override
public String chop() {
return "石斧砍柴好慢";
}
}
SteelAxe.java :public class SteelAxe implements Axe {
@Override
public String chop() {
return "钢斧砍柴好快";
}
}
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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="chinese" class="com.bean.Chinese">
<property name="axe" ref="stoneAxe"/>
</bean>
<bean id="stoneAxe" class="com.bean.StoneAxe"></bean>
<bean id="steelAxe" class="com.bean.SteelAxe"></bean>
</beans>
Test.java :public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
Person p=(Person) ctx.getBean("chinese",Person.class);
p.useAxe();
}
}
运行Test.java,控制台输出:石斧砍柴好慢。
修改bean.xml文件中 <property name="axe" ref="stoneAxe"/>的ref的值为steelAxe。再次运行Test.java,控制台输出:钢斧砍柴好快。
在配置文件里,Spring配置Bean实例通常会指定两个属性;
① id : 指定该Bean的唯一标识,程序通过id属性值来访问该Bean实例。
② class : 指定该Bean的实现类。此处不能使用接口,一定要使用实现类。
可以看到Spring管理Bean的灵巧性。Bean与Bean之间的依赖关系放在配置文件里组织,而不是写在代码里。通过配置文件的指定,Spring能精确地为每个Bean注入属性。因此配置文件里的<bean.../>元素的class属性值不能是接口,只能是真正的实现类。
结果上面的介绍,不难发现使用Spring IOC容器的3个基本要点:
⑴ 应用程序的各组件面向接口编程。面向接口编程可以将各组件之间的耦合提升到接口层次,从而有利于项目后期的扩展。
⑵ 应用程序的各组件不再由程序主动产生,而是由Spring容器来负责产生并初始化。
⑶ Spring采用配置文件或Annotation来管理Bean的实现类、依赖关系,Spring容器则根据配置文件利用反射来创建实例,并为之注入依赖关系。