构造器注入(见前贴)
Set注入【重点】
【环境搭建】
- 复杂类型
// Class Address
package cn.iris.pojo;
/**
* @author Iris 2021/8/10
*/
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
- 真实测试对象
// Class Student
package cn.iris.pojo;
import java.util.*;
/**
* @author Iris 2021/8/10
*/
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String, String> friends;
private Set<String> games;
private Properties info;
private String lady3;
}
- applicationContext.xml
//applicationContext.xml(略)
【官网Copy||IDEA直接创建】
--- 注入部分 ---
<bean class="cn.iris.pojo.Student" id="student">
<!--普通类型注入,value-->
<property name="name" value="iris"/>
<!--bean注入,ref-->
<property name="address" ref="address"/>
<!--数组-->
<property name="books">
<array>
<value>King</value>
<value>Queen</value>
</array>
</property>
<!--list-->
<property name="hobbies">
<list>
<value>Basketball</value>
<value>ComputerGames</value>
</list>
</property>
<!--map-->
<property name="friends">
<map>
<entry key="GF" value="Molly"/>
</map>
</property>
<property name="games">
<set>
<value>GTAV</value>
<value>LOL</value>
<value>CS:GO</value>
</set>
</property>
<!--null-->
<property name="lady3">
<null/>
</property>
<!--property-->
<property name="info">
<props>
<prop key="SID">201931771338</prop>
<prop key="Class">3</prop>
<prop key="driver">abaaba</prop>
<prop key="url">ip:port/abc</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
- 测试类
public class MyTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
}
}
拓展方式注入
官方解释
p命名空间注入(p-namespace)【对应Set注入】
<!--p命名空间注入,可直接注入属性的值-->
<bean id="user" class="cn.iris.pojo.User" p:name="iris" p:age="19"/>
c命名空间注入(c-namespace)【对应Constructor-arg注入】
<!--c命名空间注入,构造器注入-->
<bean id="user2" class="cn.iris.pojo.User" c:age="19" c:name="iris"/>
测试
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
User user2 = context.getBean("user2", User.class);
System.out.println(user2);
}
注意点
- p命名与c命名不能直接使用,需要导入【xml约束】
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"