How do you get current active/default Environment profile programmatically in Spring?

让人想犯罪 __ 提交于 2019-11-26 12:38:22

问题


I need to code different logic based on different current Environment profile. How can you get the current active and default profiles from Spring?


回答1:


You can autowire the Environment

@Autowired
Environment env;

Environment offers:

  • String[] getActiveProfiles(),
  • String[] getDefaultProfiles(), and
  • boolean acceptsProfiles(String... profiles)



回答2:


Extending User1648825's nice simple answer (I can't comment and my edit was rejected):

@Value("${spring.profiles.active}")
private String activeProfile;

This may throw an IllegalArgumentException if no profiles are set (I get a null value). This may be a Good Thing if you need it to be set; if not use the 'default' syntax for @Value, ie:

@Value("${spring.profiles.active:Unknown}")
private String activeProfile;

...activeProfile now contains 'Unknown' if spring.profiles.active could not be resolved




回答3:


Here is a more complete example.

Autowire Environment

First you will want to autowire the environment bean.

@Autowired
private Environment environment;

Check if Profiles exist in Active Profiles

Then you can use getActiveProfiles() to find out if the profile exists in the list of active profiles. Here is an example that takes the String[] from getActiveProfiles(), gets a stream from that array, then uses matchers to check for multiple profiles(Case-Insensitive) which returns a boolean if they exist.

//Check if Active profiles contains "local" or "test"
if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("test") 
   || env.equalsIgnoreCase("local")) )) 
{
   doSomethingForLocalOrTest();
}
//Check if Active profiles contains "prod"
else if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("prod")) )) 
{
   doSomethingForProd();
}

You can also achieve similar functionality using the annotation @Profile("local") Profiles allow for selective configuration based on a passed-in or environment parameter. Here is more information on this technique: Spring Profiles




回答4:


@Value("${spring.profiles.active}")
private String activeProfile;

It works and you don't need to implement EnvironmentAware. But I don't know drawbacks of this approach.




回答5:


If you're not using autowiring, simply implement EnvironmentAware



来源:https://stackoverflow.com/questions/9267799/how-do-you-get-current-active-default-environment-profile-programmatically-in-sp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!