Spring框架学习04——复杂类型的属性注入
代码示例如下:
创建BeanClass实体类
public class BeanClass { private String[] arrs;//数组类型 private List<String> list;//List集合类型 private Set<String> set;//Set集合类型 private Map<String,Integer> map;//Map集合类型 private Properties prop;//属性类型 //getter和setter方法 //toString()方法 }
在applicationContext.xml中配置Bean
<?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="beanClass" class="entity.BeanClass"> <!--数组类型--> <property name="arrs"> <list> <value>aa</value> <value>bb</value> </list> </property> <!--List集合--> <property name="list"> <list> <value>111</value> <value>222</value> </list> </property> <!--Set集合--> <property name="set"> <set> <value>aaa</value> <value>bbb</value> </set> </property> <!--Map集合--> <property name="map"> <map> <entry key="aa" value="11"></entry> <entry key="bb" value="22"></entry> </map> </property> <!--Properties属性--> <property name="prop"> <props> <prop key="aa">11</prop> <prop key="bb">22</prop> </props> </property> </bean> </beans>
测试代码
@Test public void demo(){ //初始化Spring容器ApplicationContext,加载配置文件 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); //通过容器获取实例 BeanClass beanClass = (BeanClass) ctx.getBean("beanClass"); System.out.println(beanClass); }
运行结果