DI依赖注入
1.构造器注入
属性下标方法注入,属性名字注入参考官方文档
<bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <!--下标从0开始--> <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<String> hobbys; //list
private Map<String,String> card; //map
private Set<String> 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> <!--list注入--> <property name="hobbys"> <list> <value>唱歌</value> <value>跳舞</value> </list> </property> <!--map注入--> <property name="card" > <map> <entry key="idcard" value="141181"/> <entry key="shuicard" value="201413"/> </map> </property> <!--set注入--> <property name="games"> <set> <value>lol</value> <value>the witcher 3</value> </set> </property> <!--空指针注入--> <property name="wife"> <null/> </property> <!--类似于配置注入注入--> <property name="info"> <props> <prop key="url">127.0.0.1</prop> <prop key="user">root</prop> <prop key="pwd">123456</prop> </props> </property>
3.拓展方式注入
p标签注入和c标签注入
使用拓展方式注入要修改命名空间。p标签可以看做<property> 无参构造器这种的 c标签可以看做是<constructor-arg>有参构造这种的

p标签使用
<bean name="classic" class="com.example.ExampleBean"> <property name="email" value="someone@somewhere.com"/> </bean> <!--使用p标签可以直接在bean 属性p:后面给属性赋值 通过属性name--> <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> <!-- c命名空间通过name匹配 --> <bean id="beanOne" class="x.y.ThingOne" c:thingTwo-ref="beanTwo" c:thingThree-ref="beanThree" c:email="something@somewhere.com"/> <!-- c命名空间通过下标匹配 --> <bean id="beanOne" class="x.y.ThingOne" c:_0-ref="beanTwo" c:_1-ref="beanThree" c:_2="something@somewhere.com"/>

浙公网安备 33010602011771号