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

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

java - Spring boot - automatically activate profile based on operating system

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...