0

I'd like to set active profile for Spring based on environment variable. To do so, I've written the following code:

@Configuration
public class SpringBootApplicationInitializer
        implements ServletContextInitializer {

    @Override
    public void onStartup(ServletContext servletContext) {

        String platform = System.getProperty("platform");

        if ("prod".equals(platform)) {
            servletContext.setInitParameter("spring.profiles.active",
                                            "prod");
        } else if ("stag".equals(platform)) {
            servletContext.setInitParameter("spring.profiles.active",
                                            "stag");
        } else {
            servletContext.setInitParameter("spring.profiles.active",
                                            "dev");
        }
    }
}

This code gets executed, however, no profile is set as Spring writes: INFO - No active profile set, falling back to default profiles: default

How do I achieve what I want?

menteith
  • 596
  • 14
  • 51

2 Answers2

2

How do I achieve what I want?

You could simply set the desired profile in the SPRING_PROFILES_ACTIVE environment variable.


What if I don't want to set this variable for dev environment? Spring will not pick up active profile then.

To address your comment, there are a number of ways to configure Spring Boot applications. If your concern is not using this environment variable for development, you'll be please to know that you can still use a properties or YAML file for development.

Just bear in mind that OS environment variables take precedence over application properties (application.properties and YAML variants). For details all configuration property sources, refer to the documentation.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Yes, of course. What if I don't want to set this variable for `dev` environment? Spring will not pick up active profile then. – menteith Feb 26 '20 at 09:19
  • @menteith You can still use a properties or YAML file for your development environment. – cassiomolin Feb 26 '20 at 09:29
0

Try like like this in application.yml

spring:
  profiles:
    active: ${platform}
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39