Spring中的set方式注入
set注入:
·依赖注入:set注入!
·依赖:bean对象的创建依赖于容器!
·注入:bean对象中的所有属性由容器来注入!
【环境搭建】
1.复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.真实测试对象
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;
3.beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.yf.pojo.Student">
<!--普通值注入,直接使用value即可-->
<property name="name" value="袁方">
</property>
</bean>
</beans>
4.测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
5.完善注入信息
<bean id="address" class="com.yf.pojo.Address">
<property name="address" value="西安"></property>
</bean>
<bean id="student" class="com.yf.pojo.Student">
<!--普通值注入,直接使用value即可-->
<property name="name" value="袁方">
</property>
<property name="address" ref="address"></property>
<property name="books">
<array>
<value>三国</value>
<value>水浒</value>
<value>红楼</value>
<value>西游</value>
</array>
</property>
<property name="hobbys">
<list>
<value>睡觉</value>
<value>打球</value>
<value>听歌</value>
</list>
</property>
<property name="card">
<map>
<entry key="身份证" value="333"></entry>
<entry key="银行卡" value="222"></entry>
<entry key="学生卡" value="111"></entry>
</map>
</property>
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<property name="wife">
<null></null>
</property>
<property name="info">
<