如何在Spring中以编程方式获取当前活动/默认环境配置文件?

Bob*_*obo 128 java spring spring-profiles

我需要根据不同的当前环境配置文件编写不同的逻辑.如何从Spring获取当前的活动和默认配置文件?

awe*_*old 188

你可以自动装配 Environment

@Autowired
Environment env;
Run Code Online (Sandbox Code Playgroud)

Environment 提供:

  • 如何在非Spring托管类中的static方法中获得此类信息? (2认同)

Mar*_*ima 53

扩展User1648825的简单答案(我无法评论,我的编辑被拒绝):

@Value("${spring.profiles.active}")
private String activeProfile;
Run Code Online (Sandbox Code Playgroud)

如果没有设置配置文件,这可能会抛出IllegalArgumentException(我得到一个空值).如果您需要设置它,这可能是一件好事; 如果不使用@Value的'default'语法,即:

@Value("${spring.profiles.active:Unknown}")
private String activeProfile;
Run Code Online (Sandbox Code Playgroud)

...如果无法解析spring.profiles.active,则activeProfile现在包含"Unknown"

  • 配置文件名称以逗号分隔。查看 https://www.baeldung.com/spring-profiles#2-using-springactiveprofile (2认同)

ana*_*ocs 40

这是一个更完整的例子.

Autowire环境

首先,您需要自动装配环境bean.

@Autowired
private Environment environment;
Run Code Online (Sandbox Code Playgroud)

检查活动配置文件中是否存在配置文件

然后,您可以使用getActiveProfiles()以查明配置文件是否存在于活动配置文件列表中.下面是一个示例,它接受String[]from getActiveProfiles(),从该数组中获取流,然后使用匹配器检查多个配置文件(Case-Insensitive),如果它们存在则返回一个布尔值.

//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();
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用注释实现类似的功能@Profile("local")以下是有关此技术的更多信息:Spring Profiles

  • @Profile似乎是最好的解决方案. (2认同)

use*_*825 23

@Value("${spring.profiles.active}")
private String activeProfile;
Run Code Online (Sandbox Code Playgroud)

它可以工作,您不需要实现EnvironmentAware.但我不知道这种方法的缺点.

  • Active profile 也可以是一个数组,请注意这一点。使用这种方式,您可能会在添加其他配置文件时遇到意外错误。 (3认同)
  • 此行给出了以下错误:`由以下原因引起:java.lang.IllegalArgumentException:无法在值"$ {spring.profiles.active}"中解析占位符'spring.profiles.active' (2认同)
  • 这种方法的缺点是它无法获取 Spring 在评估“@Profile”时可能考虑的所有配置文件。应用程序还可以使用“spring.profiles.include”属性,并可以在初始化期间使用“ConfigurableEnvironment”以编程方式设置配置文件。`Environment.getActiveProfiles()` 将使用任何这些机制获取配置文件集的完整列表。 (2认同)

naz*_*art 22

正如前面已经提到的。您可以自动装配环境

@Autowired
private Environment environment;
Run Code Online (Sandbox Code Playgroud)

只有你可以更轻松地检查所需的环境:

if (environment.acceptsProfiles(Profiles.of("test"))) {
    doStuffForTestEnv();
} else {
    doStuffForOtherProfiles();
}
Run Code Online (Sandbox Code Playgroud)


Arn*_*len 13

如果您不使用自动装配,只需实施即可 EnvironmentAware

  • 仅当实现该接口的类由 Spring 管理时才有效。 (2认同)

Mic*_*ael 11

似乎有一些需求能够静态访问它。

\n\n
\n

如何在非 spring 管理的类中的静态方法中获得这样的东西?\xe2\x80\x93 以太币

\n
\n\n

这是一个 hack,但您可以编写自己的类来公开它。您必须小心确保SpringContext.getEnvironment()在创建所有 bean 之前不会调用任何内容,因为无法保证该组件何时会被实例化。

\n\n
@Component\npublic class SpringContext\n{\n    private static Environment environment;\n\n    public SpringContext(Environment environment) {\n        SpringContext.environment = environment;\n    }\n\n    public static Environment getEnvironment() {\n        if (environment == null) {\n            throw new RuntimeException("Environment has not been set yet");\n        }\n        return environment;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n


小智 6

如果您既不想使用 @Autowire 也不想注入 @Value 您可以简单地执行以下操作(包括后备):

System.getProperty("spring.profiles.active", "unknown");
Run Code Online (Sandbox Code Playgroud)

这将返回任何活动的配置文件(或回退到“未知”)。


Syl*_*are 5

要稍微调整以处理未设置变量的情况,您可以使用默认值

@Value("${spring.profiles.active:unknown}")
private String activeProfile;
Run Code Online (Sandbox Code Playgroud)

这样,如果spring.profiles.active设置了,它将采用它,否则它将采用默认值unknown

所以不会触发任何异常。并且无需@ActiveProfiles("test")在测试中强制添加类似的内容以使其通过。