Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...