spring-boottomcat8spring-profiles

Spring Boot Programmatically setting profiles


How to set active profile in Spring Boot Application. This application will be deployed in standalone Tomcat.

I have 2 property files application-{profile}.properties.

My Application class:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
        
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {        
        return application.sources(Application.class);
    }
        
    public static void main(String[] args) {
        System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }
}

If I run the app with embedded Tomcat the dev profile is set as active and it works fine. But when I deploy in standalone Tomcat, it does not work.

I tried to set active profile in configure method. but I get NullPointerException, when I get the environment from the context.

Any help on how to set the active profile.


Solution

  • I also had the same problem and after struggling for half a day I ended up with this:

        @SpringBootApplication
        public class MyApplication extends SpringBootServletInitializer {
    
            public static void main(String[] args) {
                System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
                SpringApplication.run(MyApplication.class, args);
            }
    
            @Override
            public void onStartup(ServletContext servletContext) throws ServletException {
                System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev"); 
                super.onStartup(servletContext);
            }
        }