如果某个Bean所依赖的Bean不想被Spring容器直接访问,可以使用嵌套Bean。<bean.../>元素用来定义嵌套Bean,嵌套Bean只对嵌套它的外部Bean有效,Spring容器无法直接访问嵌套Bean,因此定义嵌套Bean时无须指定id属性。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"
>
<bean id="chinese" class="DependencyInjection.Chinese">
<property name="axe">
<bean class="DependencyInjection.StoneAxe"/>
</property>
</bean>
</beans>
package DependencyInjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanTest {
public static void main(String[] args) {
//创建Spring容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
//获取chinese实例
Person p = ctx.getBean("chinese",Person.class);
p.useAxe();
}
}
嵌套Bean提高了程序的内聚性,但降低了程序的灵活性。只有在确定无须通过Spring容器访问某个Bean实例时,才考虑使用嵌套Bean定义。