注入内部bean
当需要在一个类中使用另一个类中的内容时, 可以按前篇所说的使用注入外部bean的方式:
除此之外, 还可以使用注入内部bean的方式, 重点在于在xml文件中, 在bean内嵌套bean赋值, 以下例说明:
在Employee类中引入Department类:
Department类:
package com.ryan.spring5.quoteInsideBean; public class Department { private String dname; public void setDname(String dname) { this.dname = dname; } @Override public String toString() { return this.dname; } }
Employee类:
package com.ryan.spring5.quoteInsideBean; public class Employee { private String ename; private int eage; private Department dept; public void setEname(String ename) { this.ename = ename; } public void setEage(int eage) { this.eage = eage; } public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return this.dept + " - " + this.ename + " - " + this.eage; } }
***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.xsd"> <!--注入内部bean--> <bean id="emp" class="com.ryan.spring5.quoteInsideBean.Employee"> <property name="ename" value="张辽"></property> <property name="eage" value="28"></property> <property name="dept"> <bean id="dept" class="com.ryan.spring5.quoteInsideBean.Department"> <property name="dname" value="研发部"></property> </bean> </property> </bean> </beans>
测试:
public class Test { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("src\com\ryan\spring5\quoteInsideBean\bean.xml"); Employee emp = context.getBean("emp", Employee.class); System.out.println(emp); } }
结果:
级联赋值
级联赋值即在前篇所说的注入外部bean的基础上, 可以通过对象.属性的方式直接注入属性, 可以修改上例来演示说明:
修改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.xsd"> <!--注入内部bean--> <bean id="emp" class="com.ryan.spring5.quoteInsideBean.Employee"> <property name="ename" value="张辽"></property> <property name="eage" value="28"></property> <property name="dept" ref="dept"> </property> <!--直接注入属性--> <property name="dept.dname" value="人力资源部"></property> </bean> <bean id="dept" class="com.ryan.spring5.quoteInsideBean.Department"></bean> </beans>
需要dname可获取, 所以需要为Employee添加dept的get方法:
package com.ryan.spring5.quoteInsideBean; public class Employee { private String ename; private int eage; private Department dept; //使用级联赋值必须要有get方法 public Department getDept() { return dept; } public void setEname(String ename) { this.ename = ename; } public void setEage(int eage) { this.eage = eage; } public void setDept(Department dept) { this.dept = dept; } @Override public String toString() { return this.dept + " - " + this.ename + " - " + this.eage; } }
测试结果: