8.0、DI依赖注入环境 以及 9.0、依赖注入之set注入
·注入方式分三种:
1.普通注入
<bean id="user" class="com.hkl.User">
<property name="userID" value="0110">
</bean>
2.Bean注入
<bean id="adress" class="com.hkl.Adress" />
<bean id="user" class="com.hkl.User">
<property name="adress" ref="adress">
</bean>
3.构造注入(有参构造方法)
<bean id="user" class="com.hkl.User">
<constructor-arg name="userID" value="0110">
</bean>
8.1 Set方法注入【重点】
·依赖注入: Set注入!
·依赖:bean对象的创建依赖于Spring容器
·注入:bean对象中的所有属性,由Spring容器来注入
【环境搭建】
复杂类型,Address.java文件:
public class Address {
private String address;
Public String getAddress(){
Return address;
}
Public String setAddress(String address){
This.address = address;
}
}
真实测试对象,Student.java文件:
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> card;
private Set<String> games;
private String wife;
private properties info;
}
xml文件 beans.xml
<!--String类型注入方式-->
<bean id = "address" class = "com.hkl.Address">
<property name = "address" value="北京" />
</bean>
<!--bean类型注入方式-->
<bean id = "student" class = "com.hkl.Student">
<property name = "name" value = "小明" />
<property name = "adress" ref = "address" />
<!--数组类型对象注入-->
<property name = "books">
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</property>
<!--list类型对象注入-->
<property name = "hobbys">
<arry>
<value>听歌</value>
<value>看电影</value>
<value>刷题</value>
</arry>
</property>
<!--Map类型对象注入-->
<property name = "card">
<map>
<entry key="身份证" value="111111222222223333">
<entry key="银行卡" value="121231231321321332">
</map>
</property>
<!--Set类型对象注入-->
<property name = "games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--设置为null,null类型对象注入-->
<property name = "wife">
<null/>
</property>
<!--Properties类型对象注入-->
<property name = "info">
<props>
<prop key = "学号">199050366</prop>
<prop key = "性别">男</prop>
<prop key = "姓名">小明</prop>
</props>
</property>
</bean>