有没有办法防止bean覆盖Spring Boot?

Haz*_*zok 5 java spring spring-boot

使用Spring的AbstractRefreshableApplicationContext,如果Bean ID或循环引用中存在冲突,我可以通过设置几个标志并刷新上下文来强制Spring失败:

AbstractRefreshableApplicationContext refreshableContext;
...
refreshableContext.setAllowBeanDefinitionOverriding(false);
refreshableContext.setAllowCircularReferences(false);
refreshableContext.refresh();
Run Code Online (Sandbox Code Playgroud)

但是,Spring Boot返回ConfigurableApplicationContext,它不是AbstractRefreshableApplicationContext的实例,并且似乎没有任何方法可以阻止bean定义覆盖或循环引用.

有没有人知道一种方法,并有一个如何防止这些类型的冲突的例子?

对于上下文,这适用于具有带注释和xml定义bean组合的大型项目.使用的Spring Boot版本是1.3.1.RELEASE.在某些情况下,人们在xml中添加了重复的bean定义,但是应用程序启动正常,并且在启动运行时问题之前,原始bean被覆盖并不是很明显.

这里的目标是在发生此类冲突时阻止应用程序启动事件.从各种论坛我知道Spring IDE可以检测到这些,但是希望在CI构建中强制执行这个,这是一个更强大的安全网.

经过一些搜索,我在Sprint Boot返回的上下文中找不到任何支持.如果无法通过上下文完成此操作,是否有可用的其他解决方案?

提前致谢.

ale*_*xbt 9

在构建Spring Boot应用程序时,您可以使用初始化程序:

@SpringBootApplication
public class SpringBootApp {

    public static void main(String... args) {
        new SpringApplicationBuilder(SpringBootApp.class)
            .initializers(new ApplicationContextInitializer<GenericApplicationContext>() {
                @Override
                public void initialize(GenericApplicationContext applicationContext) {
                    applicationContext.setAllowBeanDefinitionOverriding(false);
                }
            })
        .run(args);

    }
}
Run Code Online (Sandbox Code Playgroud)

或者使用java 8:

new SpringApplicationBuilder(SpringBootApp.class)
    .initializers((GenericApplicationContext c) -> c.setAllowBeanDefinitionOverriding(false) )
    .run(args);
Run Code Online (Sandbox Code Playgroud)


Aur*_*ura 6

将以下添加到您的 application.yml 中

spring.main.allow-bean-definition-overriding: false
Run Code Online (Sandbox Code Playgroud)