Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...