Spring IOC
IoC (Inversion Of Control)中文名为控制反转,就是由容器来控制业务对象之间的依赖关系,而非传统实现中,由代码直接操控。这也就是所谓“控制反转”的概念所在:控制权由应用代码中转到了外部容器,控制权的转移,是所谓反转。控制权的转移带来的好处就是降低了业务对象之间的依赖程度。
1) 依赖查找:容器中的受控对象通过容器的API来查找自己所依赖的资源和协作对象。这种方式虽然降低了对象间的依赖,但是同时也使用到了容器的API,造成了我们无法在容器外使用和测试对象。
2) 依赖注入:对象只提供普通的方法让容器去决定依赖关系,容器全权负责组件的装配,它会把符合依赖关系的对象通过属性(JavaBean中的 getter和setter,.NET中的property)或者是构造子传递给需要的对象。通过属性注射依赖关系的做法称为设值方法注入(Setter Injection),将构造子参数传入的做法称为构造子注入(Constructor Injection)
BeanFactory factory=new XmlBeanFactory(resource);
1) 依赖查找:容器中的受控对象通过容器的API来查找自己所依赖的资源和协作对象。这种方式虽然降低了对象间的依赖,但是同时也使用到了容器的API,造成了我们无法在容器外使用和测试对象。
2) 依赖注入:对象只提供普通的方法让容器去决定依赖关系,容器全权负责组件的装配,它会把符合依赖关系的对象通过属性(JavaBean中的 getter和setter,.NET中的property)或者是构造子传递给需要的对象。通过属性注射依赖关系的做法称为设值方法注入(Setter Injection),将构造子参数传入的做法称为构造子注入(Constructor Injection)
(一)设值方法注入(Setter Injection)
通过 JavaBean 的属性(例如 setter 方法)分配依赖性
java代码: |
<bean id="exampleBean" class="examples. ExampleBean"> <property name="beanOne"><ref bean="bean1"/></property> <property name="beanTwo"><ref bean="bean2"/></property> <property name="count"><value> 1</value></property> </bean> <bean id="bean1" class="examples. BeanOne"/> <bean id="bean2" class="examples. BeanTwo"/> |
(二)构造子注入(Constructor Injection)
依赖性以构造函数的形式提供,不以 JavaBean 属性的形式公开
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg><ref bean="bean1"/></constructor-arg>
<constructor-arg><ref bean="bean2"/></constructor-arg>
<constructor-arg><value>1</value></constructor-arg>
</bean>
<bean id="bean1" class="examples.BeanOne"/>
<bean id="bean2" class="examples.BeanTwo"/>
附:
ClassPathXmlApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {
"springexample-creditaccount.xml"});
Resource resource=new ClassPathResource("com/bean.xml");
BeanFactory factory=new XmlBeanFactory(resource);