spring 依赖注入总结

来源:互联网 发布:金蝶智慧记mac版 编辑:程序博客网 时间:2024/05/16 10:15

spring 依赖注入总结

一、 set 方法注入

1 、基本格式:

<bean id=”foo”>

<property name=”name”>

<value>tom</value>

</property>

</bean>

2 、引用其他 bean

<bean id=”foo”>

<property name=”name”>

<ref bean=”bar”>

</property>

</bean>

<bean id=”bar”>

3 、内部 bean( 其他 bean 无法重用此内部 bean)

<bean id=”foo”>

<property name=”bar”>

<bean class=”…Bar”>

</property>

</bean>

4 、装配集合( List )

<property name=”barlist”>
<list>

<value>bar1</value>

<ref bean=”bar2”/>

<list>

</property>

<!—spring2.5 à

<Util:list>

5 、装配集合( set )

注意: value值不能重复,重复的部分只取其一

<property name=”barlist”>

<set>

<value>bar1</value>

<ref bean=”bar2”/>

</set>

</property>

<Util:set>

6 、装配 map:key 之必须是 String 的 ,key-ref 可以是其他 bean

<property name=”barlist”>

<map>

<entry key=”key1” value=”bar1”/>

<entry key=”key2” value-ref=”xxx”/>

</map>

</property>

<!—spring2.5 à

<util:map>

7 、装配 properties :

<property name=”barlist”>

<props>

<prop key=”key1”>bar1</prop>

<prop key=”key1”>bar1</prop>

</props>

</property>

<!—spring2.5 à

<util:properties>

8 、若 bean 的属性是集合类型,按如下处理:设置 null :

<property name=”barlist”>

<null/>

</property>

二、通过构造函数注入依赖

<bean id=”foo”>

<constructor-arg>

<value>42</value>

</constructor-arg>

</bean>

<bean id=”foo”>

<constructor-arg>

<ref bean=”bar”>

</constructor-arg>

</bean>

Set 注入的缺点是无法清晰表达哪些属性是必须的,那些是可选的,构造注入的优势是通过构造强制依赖关系,不可能实例化不能完全或无法使用的 bean

1、解决构造函数参数不确定性

通过参数的顺序;

<constructor-argindex=0>

<value>http://www.tom.com</value>

</constructor>

<constructor-argindex=1>

<value>bar1</value>

</constructor>

2 、解决构造函数参数不确定性

通过参数的类型:

<constructor-argtype="java.lang.String">

<value>http://www.tom.com</value>

</construcotr-arg>

<constructor-argjava.lang.URL>

<value>bar1</value>

</construcotr-arg>

原创粉丝点击