依赖注入、Bean的自动装配等
6、依赖注入
6.1、构造器注入
之前写的
6.2、Set方式注入【重点】
-
依赖注入:Set注入!
-
依赖:bean对象的创建依赖于容器
-
注入:bean对象中的所有属性,由容器来注入!
-
【环境搭建】
-
复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} -
真实测试对象
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;
}
-
beans.xml
-
测试类
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());
}
} -
完善注入信息
<bean id="address" class="com.kuang.pojo.Address">
<property name="address" value="南昌"></property>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
<!-- 第一种,普通值注入,value-->
<property name="name" value="荣哥"></property>
<!-- 第二种,Bean注入,ref-->
<property name="address" ref="address"></property>
<!-- 数组-->
<property name="books" >
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!-- List-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<!-- Map-->
<property name="card">
<map>
<entry key="身份证" value="12121242"></entry>
<entry key="银行卡" value="124253434"></entry>
</map>
</property>
<!-- Set-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
</set>
</property>
<!-- null-->
<property name="wife">
<null/>
</property>
<!-- Properties-->
<