对于Spring的父子工厂:
- 父工厂和子工厂的配置会整合在一起
- 如果父子工厂中存在相同的配置,会采用子工厂的配置
代码:
父工厂applicationContext-parent.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 id="p" class="edu.hzb.first.Person">
</bean>
<bean id="user" class="edu.hzb.first.User">
<property name="id" value="2"/>
<property name="name" value="jeremy"/>
</bean>
</beans>
子工厂applicationContext-child.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 id="user" class="edu.hzb.first.User">
<property name="id" value="1"/>
<property name="name" value="hzb"/>
</bean>
</beans>
测试代码:
@Test
public void test3() {
//父容器
DefaultListableBeanFactory parent = new DefaultListableBeanFactory();
XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(parent);
xmlBeanDefinitionReader.loadBeanDefinitions(new ClassPathResource("applicationContext-parent.xml"));
//子容器
DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent);
XmlBeanDefinitionReader xmlBeanDefinitionReader1 = new XmlBeanDefinitionReader(child);
xmlBeanDefinitionReader1.loadBeanDefinitions(new ClassPathResource("applicationContext-child.xml"));
Person p = (Person) child.getBean("p");
User user = (User) child.getBean("user");
System.out.println(p);
System.out.println(user);
//这个user仍然是子容器中的user
User user1 = (User) parent.getBean("user");
System.out.println(user);
}
学习哔哩哔哩《孙哥讲Spring5》视频所做的笔记