Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Bean only for embedded tomcat or embedded server

Tags:

spring-boot

I want @Bean to be created if application is running in embedded container. That bean should not be created if application is run on external tomcat. Is there any way we can create @Conditional annotation to create bean only if application is running in embedded tomcat.

like image 287
Amit Gadkari Avatar asked Jan 21 '16 12:01

Amit Gadkari


People also ask

Does spring boot use embedded Tomcat?

By default, Spring Boot provides an embedded Apache Tomcat build. By default, Spring Boot configures everything for you in a way that's most natural from development to production in today's platforms, as well as in the leading platforms-as-a-service.

Can we use embedded Tomcat in production?

Yes. It's the same tomcat, but in library form. So you are responsible for configuration and other things that the standalone tomcat provides. Also you don't have to use tomcat.

What is embedded Tomcat server?

An embedded Tomcat server consists of a single Java web application along with a full Tomcat server distribution, packaged together and compressed into a single JAR, WAR or ZIP file.

Can we override or replace the embedded Tomcat server in spring boot?

If you'd like to change the embedded web server to Jetty in a new Spring Boot web starter project, you'll have to: Exclude Tomcat from web starter dependency, since it is added by default. Add the Jetty dependency.


1 Answers

Rather than using a custom condition, you could use a Spring profile that's only enabled when you're using an embedded container. When you deploy a Spring Boot application to Tomcat its main method isn't run, making it a good place to enable the profile that you only want to be active in the embedded case.

Something like this:

@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);
    }
}
like image 50
Andy Wilkinson Avatar answered Nov 15 '22 09:11

Andy Wilkinson