1、组合属性名值注入:
package com.sxit.service; public class Chinese{ private ChinesePerson person = new ChinesePerson(); public ChinesePerson getPerson() { return person; } public void setPerson(ChinesePerson person) { this.person = person; } }
2、xml配置文件:
<?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-3.0.xsd "> <bean id="chinese" class="com.sxit.service.Chinese"> <property name="person.type" value="中国人"/> </bean> </beans>
3、 测试类及打印信息:
package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.sxit.service.Chinese; public class Test { public static void main(String[] args) { ApplicationContext apc = new ClassPathXmlApplicationContext("Bean.xml"); Chinese chinese = apc.getBean("chinese",Chinese.class); System.out.println(chinese.getPerson().getType()); } } 中国人
4、注意:
1)、private ChinesePerson person = new ChinesePerson();此处一定要new一个实例,person不能为null,否则会引发空指针异常。 2)、注入的过程是:先getPerson(),然后再setType()....,即Chinese.getPerson().setType("中国人")。 3)、所以组合属性注入最后一层属性是调用set方法外,其他层都是先调用get方法获取,如果为空,则引发异常。