Spring boot - automatically activate profile based on operating system

Viewed 764

Let's say I have a spring profile that is specific to a particular operating system:

spring:
  profiles: mac
  cloud:
    zookeeper:
      discovery:
        preferIpAddress: false
        instanceHost: docker.for.mac.localhost

Is there some way to automatically enable a spring profile based on the current operating system?

So in my case, I want the above profile to automatically become active if it is on a Darwin os.

Maybe there is some way to do it with system properties? In this case, I want the mac profile to be active if os.name contains "Darwin"?

Any ideas?

3 Answers

something like this would work for you? Of course you should adjust the condition.

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication app = new SpringApplication(DemoApplication.class);
    if (System.getProperty("os.name").contains("darwin")) {
      app.setAdditionalProfiles("mac");
    }
    app.run(args);
  }

}

If you have the environment variables to determine OS type then you can do it Programmatically

Programmatically via WebApplicationInitializer Interface

In web applications, WebApplicationInitializer can be used to configure the ServletContext programmatically.

It's also a very handy location to set our active profiles programmatically:

@Configuration
public class MyWebApplicationInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

   if (System.getProperty("os.name").contains("darwin")) {
  servletContext.setInitParameter("spring.profiles.active", "mac");
     }
    
  }
}

If you don't want to hard code in application or create config class, then I would recommend setting env variables based on OS

SPRING_PROFILES_ACTIVE=mac

In the normal Spring way, you can use a spring.profiles.active Environment property to specify which profiles are active

if you have a start shell script in each environment. you could choose active profile. for example, java -jar yourApplication.jar --spring.profiles.active=mac

Related