这里面也没什么好解释的了,主要是熟悉代码就好了。下面直接给出代码
1、实体代码
package spring.injection;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class CollectionBean {
private Object[] arr; //数据类型注入
private List list; //list/set 类型注入
private Map map; //map类型注入
private Properties prop;//Properties类型注入
public Object[] getArr() {
return arr;
}
public CollectionBean() {
super();
}
public void setArr(Object[] arr) {
this.arr = arr;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public Properties getProp() {
return prop;
}
public void setProp(Properties prop) {
this.prop = prop;
}
@Override
public String toString() {
return "CollectionBean [arr=" + Arrays.toString(arr) + ", list=" + list + ", map=" + map + ", prop=" + prop
+ "]";
}
}
2、applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<bean name="user" class="spring.bean.User" >
<property name="name" value="aa"></property>
<property name="age" value="16"></property>
</bean>
<!-- 复杂类型注入 -->
<!--array注入 -->
<bean name="a" class="spring.injection.CollectionBean">
<!-- 如果数组中只准备注入一个值 (对象),那么直接使用value或ref
<property name="arr" value="tom "></property> -->
<property name="arr">
<array>
<value>tom</value>
<value>jerrt</value>
<ref bean="user"/>
</array>
</property>
<!-- list注入 -->
<!-- 如果list中只准备注入一个值 (对象),那么直接使用value或ref
<property name="list" value="da"></property>-->
<property name="list">
<list>
<value>tom</value>
<value>jerrt</value>
<ref bean="user"/>
</list>
</property>
<!-- map注入 -->
<property name="map">
<map>
<entry key="123" value="abc"></entry>
<entry key="user1" value-ref="user"></entry>
</map>
</property>
<!-- properties注入 -->
<property name="prop">
<props>
<prop key="qwe">asd</prop>
</props>
</property>
</bean>
</beans>
3、测试
package spring.injection;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.bean.User;
public class Demo1 {
@Test
public void fun1(){
//1、创建容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("spring/injection/applicationContext2.xml");
//2、向容器要对象
CollectionBean u = (CollectionBean) ac.getBean("a");
System.out.println(u);
}
}