如何在春季停止覆盖bean [英] How to stop overiding a bean in Spring
问题描述
我注意到,如果您在两个xml文件中定义一个具有相同ID的bean,它将在第二个文件中被覆盖.
I noticed that if you define a bean with same id in two xml files, it would be overiden in the second file.
Say in file a.xml i have
<bean id="abc" />
Say in file b.xml i have
<bean id="abc" />
然后拾取b.xml的bean"abc".在Spring中有没有一种方法可以停止覆盖,即无论有多少xml的abc豆,它都应该是唯一的.
then the bean "abc" of b.xml is picked up. Is there a way in Spring to stop from overiding i.e should be unique no matter how many xml have the bean abc.
推荐答案
您可以通过调用setAllowBeanDefinitionOverriding
并传递false
来禁用该功能以禁止bean覆盖.必须在加载任何内容之前尽早进行此操作.您可能需要为此创建自己的自定义ContextLoader
,或者(如果您使用的是Spring 3.1或更高版本)可以创建ApplicationContextInitializer
并将其注册到web.xml中.
You can disable the feature to disallow beanoverriding by calling the setAllowBeanDefinitionOverriding
and pass false
. This has to be done early on before anything is loaded. You would either need to create your own custom ContextLoader
for this or (if you are on Spring 3.1 or up) you can create an ApplicationContextInitializer
and register this in your web.xml.
public class OverrideDisablingApplicationContextInitializer implements ApplicationContextInitializer {
public void void initialize(<? extends ConfigurableApplicationContext> applicationContext);
if (applicationContext instanceof AbstractRefreshableApplicationContext) {
(AbstractRefreshableApplicationContext (applicationContext)).setAllowBeanDefinitionOverriding(false);
}
}
在web.xml中添加以下内容(对于ContextLoaderListener
,在需要时对DispatcherServlet
使用init-param)
in your web.xml add the following (for the ContextLoaderListener
use an init-param for the DispatcherServlet
when needed)
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>your.package.here.OverrideDisablingApplicationContextInitializer<param-value>
</context-param>
从我的头顶开始,这应该禁用主要行为.如果您使用springs WebApplicationInitializer,则可能更容易,因为您可能自己构造ApplicationContext
,则可以直接直接调用该方法,而无需ApplicationContextInitializer
.
From the top of my head this should disable the overriding behavior. If you use springs WebApplicationInitializer it is even easier as you are probably constructing the ApplicationContext
yourself, you can then simply call the method directly and no ApplicationContextInitializer
is needed.
链接
- ApplicationContextInitializer javadoc
- AbstractRefreshableApplicationContext.setAllowBeanDefinitionOverriding javadoc
- ApplicationContextInitializer javadoc
- AbstractRefreshableApplicationContext.setAllowBeanDefinitionOverriding javadoc
这篇关于如何在春季停止覆盖bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!