Spring属性注入【三】 复杂类型注入

xiaoxiao2021-02-28  7

P名称空间注入

applicationContext.xml配置文件:

//引用 xmlns:p="http://www.springframework.org/schema/p" <!-- P名称空间注入 --> <bean id="person" class="Person全路径" p:pname="Bob"></bean>

复杂类型注入

复杂类型:

1、数组2、list集合3、map集合4、properties类型

具体实现:

Person类:

public class Person{ private String pname; public void setPname(String pname){ this.pname = pname; } private String [] arrs; private List<String> list; private Map<String,String> map; private Properties properties; //util包中的Peoperties //生成属性的set方法,此处略去 public void test(){ System.out.println("arrs:"+arrs); System.out.println("list:"+list); System.out.println("map:"+map); System.out.println("properties:"+properties); } }

applicationContext.xml配置文件:

<!-- 注入复杂类型属性值 --> <bean id="person" class="Person全路径"> <!-- 数组 --> <property name="arrs"> <list> <value>Bob</value> //数组中第一个值 <value>Tom</value> //数组中第二个值 <value>john</value> //数组中第三个值 </list> </property> <!-- list --> <property name="list"> <list> <value>aaa</value> //list中第一个值 <value>bbb</value> //list中第二个值 <value>ccc</value> //list中第三个值 </list> </property> <!-- map --> <property> <map> <entry key="aa" value="11"></entry> <entry key="bb" value="12"></entry> <entry key="cc" value="13"></entry> </map> </property> <!-- properties --> <property name="properties"> <props> <prop key="driverclass">com.mysql.jdbc.Driver</prop> <prop key="username">root</prop> <prop key="password">123456</prop> </props> </property> </bean>

测试方法:

public void testUser(){ //1、加载spring配置文件,根据创建对象 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //2、得到配置创建对象 Person person = (Person) context.getBean("person"); person.test(); }

注:

本文是我自学笔记总结,不足之处,还望指正,谢谢。

转载请注明原文地址: https://www.6miu.com/read-2500154.html

最新回复(0)