- 如果bean依赖bean不想被spring直接访问,可以使用嵌套bean
- 嵌套的bean仅仅作为setter方法的参数而已。所以无需指定id
- 程序结构
<?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="exampleField" class="ExampleBean"> <property name="tea"> <bean class="Test"/> <!--嵌套bean,作为setTea的参数--> </property> </bean> </beans>
public class ExampleBean { private String tea; public String getTea() { return tea; } public void setTea(Test test) { this.tea = test.getTea(); } }
public class Test { private String tea = "oo"; public String getTea() { return tea; } // // public void setTea(String tea) { // this.tea = tea; // } }
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 测试类,测试有没有被赋值成功 */ public class SpringTest { public static void main(String []args){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); ExampleBean exampleBean = (ExampleBean)applicationContext.getBean("exampleField",ExampleBean.class); System.out.println(exampleBean.getTea()); } }
这是我看李刚编著的《轻量级javaEE企业应用实战(第五版)-Struts2+Spring5+Hibernate5/JAP2》后总结出来的。
Spring(8) 注入嵌套bean
最新推荐文章于 2021-05-17 17:33:14 发布