Is there a way to prevent bean redefinition using Spring Boot?

With Spring AbstractRefreshableApplicationContext , I can get Spring to fail if there is a conflict in the Bean ID or circular links by setting a couple of flags and updating the context as follows:

AbstractRefreshableApplicationContext refreshableContext;
...
refreshableContext.setAllowBeanDefinitionOverriding(false);
refreshableContext.setAllowCircularReferences(false);
refreshableContext.refresh();

However, Spring Boot returns a ConfigurableApplicationContext , which is not an instance of AbstractRefreshableApplicationContext and, apparently, has no means to prevent Bean redefinition or circular reference definitions.

Does anyone know a way and example of how to prevent these types of conflicts?

For context, this is for a large project in which there is a combination of annotated and xml defined beans. Spring version Used download: 1.3.1.RELEASE. There were cases when people added duplicate Bean definitions to the xml, but the application started normally and it was not immediately clear that the original Bean was redefined until there were problems with the launch.

The goal is to prevent the application from starting when such a conflict occurs. In various forums, I know that the Spring IDE can detect them, but the desire to provide this is in the CI assembly, which is a more reliable security network.

After some searching, I cannot find support for this in the context that Sprint Boot returns. If this cannot be done through context, is there another solution?

Thanks in advance.

+4
1

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);

    }
}

java 8:

new SpringApplicationBuilder(SpringBootApp.class)
    .initializers((GenericApplicationContext c) -> c.setAllowBeanDefinitionOverriding(false) )
    .run(args);
+5

Source: https://habr.com/ru/post/1650333/


All Articles