依赖注入:Set注入!
- 依赖:bean对象的创建依赖于容器!
- bean对象中的所有属性,由容器来注入!
【环境搭建】
1、复杂环境
package com.gwq.pojo;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class Address {
private String address;
}
2、真实测试对象
package com.gwq.pojo;
import lombok.Data;
import lombok.ToString;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@Data
@ToString
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobby;
private Map<String,String> card;
private Set<String> games;
private String wife;
private Properties info;
}
applicationContext.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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.gwq.pojo.Address"/>
<bean id="student" class="com.gwq.pojo.Student">
<!-- 第一种,普通值注入,value -->
<property name="name" value="gwq"/>
<!-- 第二种,Bean注入,ref -->
<property name="address" ref="address"/>
<!-- 第三种,数组注入 -->
<property name="books">
<array>
<value>平凡的世界1</value>
<value>平凡的世界2</value>
<value>平凡的世界3</value>
</array>
</property>
<!-- 第四种,list注入 -->
<property name="hobby">
<list>
<value>听歌</value>
<value>代码</value>
<value>电影</value>
</list>
</property>
<!-- Map -->
<property name="card">
<map>
<entry key="身份证" value="123345676"></entry>
</map>
</property>
<!-- Set -->
<property name="games">
<set>
<value>LOL</value>
<value>OW</value>
</set>
</property>
<!-- null -->
<property name="wife">
<null/>
</property>
<!-- Properties -->
<property name="info">
<props>
<prop key="学号">201923</prop>
<prop key="性别">男</prop>
<prop key="账号">root</prop>
</props>
</property>
</bean>
</beans>
测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
}
}
//Student(name=gwq, address=Address(address=null),
// books=[平凡的世界1, 平凡的世界2, 平凡的世界3],
// hobby=[听歌, 代码, 电影],
// card={身份证=123345676},
// games=[LOL, OW],
// wife=null,
// info={学号=201923, 性别=男, 账号=root})