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

前端 未结 6 929
梦毁少年i
梦毁少年i 2020-11-29 19:17

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

6条回答
  •  误落风尘
    2020-11-29 20:04

    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

提交回复
热议问题