allowBeanDefinitionOverriding属性含义
设置是否允许通过注册具有相同名称的不同定义来覆盖bean定义,并自动替换前者。否则,将引发异常。默认值为“true”。
allowCircularReferences属性含义
设置是否允许bean之间的循环引用并自动尝试解析它们。
默认值为“true”。关闭此选项可在遇到循环引用时引发异常,完全不允许循环引用。
循环依赖应该都比较了解,主要看看allowBeanDefinitionOverriding。
public class TestSpring {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml", "bean2.xml");
User user = (User) applicationContext.getBean("user");
System.out.println("name: " + user.getName());
}
}
加载了两个配置文件,并且都配置了id为user的bean对象。
bean1.xml中,name为lisi
<bean id="user" class="com.wyl.learn.User">
<property name="name" value="lisi"></property>
<property name="age" value="18"></property>
</bean>
bean2.xml中,name为wangwu
<bean id="user" class="com.wyl.learn.User">
<property name="name" value="wangwu"></property>
<property name="age" value="18"></property>
</bean>
根据allowBeanDefinitionOverriding属性的定义,默认值为true,并且相同名称的bean会进行覆盖,所以按照xml文件的加载顺序,bean2会覆盖bean1的配置。
最终输出结果为:name: wangwu
如果交换配置文件的加载顺序
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean2.xml", "bean.xml");
最终输出结果为:name: lisi
如何修改属性值
方式一:
自定义一个applicationContext,并继承ClassPathXmlApplicationContext,重写customizeBeanFactory方法。
public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext {
public MyClassPathXmlApplicationContext(String... configLocations) {
super(configLocations);
}
@Override
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
super.setAllowBeanDefinitionOverriding(false);
super.setAllowCircularReferences(false);
super.customizeBeanFactory(beanFactory);
}
}
public class TestSpring {
public static void main(String[] args) {
MyClassPathXmlApplicationContext applicationContext = new MyClassPathXmlApplicationContext("bean2.xml", "bean1.xml");
User user = (User) applicationContext.getBean("user"

本文详细介绍了Spring框架中allowBeanDefinitionOverriding属性的作用及其应用场景,包括如何通过自定义上下文和设置方法禁止Bean定义覆盖,避免因加载顺序不同导致的Bean定义冲突。

3405

被折叠的 条评论
为什么被折叠?



