spring属性注入—复杂类型注入
实体
package cn.itcast.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; private Map map; private Properties prop; public Object[] getArr() { return arr; } 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 + "]"; } }
xml配置
<!-- ============复杂类型注入================== --> <!-- array注入 --> <bean name="cb" class="cn.itcast.injection.CollectionBean"> <!--如果数组中只准备注入一个值或者对象,直接使用value或者ref即可 --> <!-- <property name="arr" value="tom"></property> --> <!-- array注入 --> <property name="arr"> <array> <value>tom</value> <value>tom</value> <ref bean="user4"/> </array> </property> <!--如果list中只准备注入一个值或者对象,直接使用value或者ref即可 --> <!-- <property name="list" value="jack"></property> --> <!-- List 注入 --> <property name="list"> <list> <value>tom</value> <value>tom</value> <ref bean="user3"/> </list> </property> <!--map类型注入 --> <property name="map"> <map> <entry key="url" value="jdbc:mysql"></entry> <entry key="user" value="user3"></entry> </map> </property> <!-- properties类型注入 --> <property name="prop"> <props> <prop key="username"> root </prop> <prop key="password"> 123 </prop> </props> </property>
demo例子
public class Demo { @Test public void test1(){ //1、创建容器对象 ApplicationContext ac =new ClassPathXmlApplicationContext("cn/itcast/injection/applicationContext.xml"); //2、像容器要User对象 CollectionBean cb = (CollectionBean)ac.getBean("cb"); //3、打印user对象 System.out.println(cb.toString()); } }
结果: