Creating a Bean only for embedded tomcat or embedded server

I want @ Bean to be created if the application is running in an embedded container. That the bean should not be created if the application is running on an external tomcat. Is it possible to create @Conditional annotation to create a bean only if the application is running in the built-in tomcat.

+4
source share
2 answers

Instead of using a custom condition, you can use the Spring profile, which is only allowed when using the built-in container. When you deploy the Spring boot application to Tomcat, its main method does not start, which makes it a good place to include the profile that you only want to be active in the built-in case.

Something like that:

@SpringBootApplication
public class So34924050Application extends SpringBootServletInitializer {

    @Bean
    @Profile("embedded")
    public EmbeddedOnlyBean embeddedOnlyBean() {
        return new EmbeddedOnlyBean();
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(So34924050Application.class);
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(So34924050Application.class).profiles("embedded").run(args);
    }
}
+3
source

I used the annotation @ConditionalOnClassto create only TomcatFactory if embedded Tomcat classes exist . If this is not suitable for your purposes, there are many classes @CondtionalOn...that you could use to conditionally create a bean. for example @CondtionalOnProperty.

i.e.

// If running tomcat embedded, ensure that JNDI is enabled.
@Bean
@ConditionalOnClass(name = {
        "org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory",
        "org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer",
        "org.apache.catalina.startup.Tomcat"
})
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {
        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(final Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}
+1
source

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


All Articles