DI依赖注入
1.构造器注入
属性下标方法注入,属性名字注入参考官方文档
<bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> <constructor-arg name="pwd" value="123456"/> bean>
2.set方式注入(重点)
注入bean基本属性 | ref 引用类 | list | set | map | props | value | null
private String name; //姓名
private Address address; //引用类型
private String[] books; //数组
private List hobbys; //list
private Map card; //map
private Set games; //set
private String wife; //是否有老婆 注入空指针
private Properties info; //信息
<property name="name" value="小陈"/>
<property name="address" ref="address"/>
<property name="books">
<array>
<value>Spring入门到精通value>
<value>Java入门到精通value>
array>
property>
<property name="hobbys">
<list>
<value>唱歌value>
<value>跳舞value>
list>
property>
<property name="card" >
<map>
<entry key="idcard" value="141181"/>
<entry key="shuicard" value="201413"/>
map>
property>
<property name="games">
<set>
<value>lolvalue>
<value>the witcher 3value>
set>
property>
<property name="wife">
<null/>
property>
<property name="info">
<props>
<prop key="url">127.0.0.1prop>
<prop key="user">rootprop>
<prop key="pwd">123456prop>
props>
property>
3.拓展方式注入
p标签注入和c标签注入
使用拓展方式注入要修改命名空间。p标签可以看做
p标签使用
<bean name="classic" class="com.example.ExampleBean"> <property name="email" value="someone@somewhere.com"/> bean> <bean name="p-namespace" class="com.example.ExampleBean" p:email="someone@somewhere.com"/>
c标签使用
<bean id="beanTwo" class="x.y.ThingTwo"/> <bean id="beanThree" class="x.y.ThingThree"/> <bean id="beanOne" class="x.y.ThingOne"> <constructor-arg name="thingTwo" ref="beanTwo"/> <constructor-arg name="thingThree" ref="beanThree"/> <constructor-arg name="email" value="something@somewhere.com"/> bean> <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo" c:thingThree-ref="beanThree" c:email="something@somewhere.com"/> <bean id="beanOne" class="x.y.ThingOne" c:_0-ref="beanTwo" c:_1-ref="beanThree" c:_2="something@somewhere.com"/>