我需要根据不同的当前环境配置编写不同的逻辑。
你如何从Spring中获取当前活动和默认配置文件?
我需要根据不同的当前环境配置编写不同的逻辑。
你如何从Spring中获取当前活动和默认配置文件?
acceptsProfiles(String... profiles)
方法,并用acceptsProfiles(Profiles profiles)
方法替换了它。 - M. Justin扩展User1648825简短明了的回答:
@Value("${spring.profiles.active}")
private String activeProfile;
如果没有设置配置文件(我得到一个空值),则可能会抛出IllegalArgumentException异常。 如果需要设置它,则这可能是一件好事; 如果不需要,请使用@Value的“default”语法,即:
如果没有配置文件,则@Value使用默认值。例如:@Value($ {'my.property:default'})
@Value("${spring.profiles.active:Unknown}")
private String activeProfile;
如果无法解析spring.profiles.active,则activeProfile
现在包含“Unknown”
这里有一个更完整的例子。
自动装配环境
首先,您需要自动装配环境bean。
@Autowired
private Environment environment;
检查活动配置文件中是否存在配置文件
接下来,您可以使用getActiveProfiles()
来查找该配置文件是否存在于活动配置文件列表中。以下是一个示例,它获取来自getActiveProfiles()
的String[]
,从该数组获取一个流,然后使用匹配器检查多个配置文件(不区分大小写),如果它们存在,则返回布尔值。
//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();
}
您还可以使用注释@Profile("local")
实现类似的功能,根据传入的参数或环境参数进行选择性配置。有关此技术的更多信息,请参见:Spring Profiles
@Value("${spring.profiles.active}")
private String activeProfile;
这个方法是可行的,而且不需要实现EnvironmentAware。但我不知道这种方法的缺点。
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.profiles.active' in value "${spring.profiles.active}"
。 - zygimantus@Profile
时可能考虑的所有配置文件。应用程序还可以使用spring.profiles.include
属性,并且可以在初始化期间使用ConfigurableEnvironment
编程设置配置文件。Environment.getActiveProfiles()
将获取使用任何这些机制设置的完整配置文件列表。 - Scott Frederick如前所述,您可以使用自动装配来注入Environment:
@Autowired
private Environment environment;
只有您可以更轻松地检查所需环境:
if (environment.acceptsProfiles(Profiles.of("test"))) {
doStuffForTestEnv();
} else {
doStuffForOtherProfiles();
}
如果您没有使用自动装配,请简单实现 EnvironmentAware
接口
似乎有一些需求可以静态访问此内容。
如何在非 Spring 管理的类中的静态方法中获得这种功能?- Aetherus
这是一个 hack,但您可以编写自己的类来公开它。您必须小心确保在所有 bean 创建之前没有任何东西会调用 SpringContext.getEnvironment()
,因为无法保证何时将实例化此组件。
@Component
public class SpringContext
{
private static Environment environment;
public SpringContext(Environment environment) {
SpringContext.environment = environment;
}
public static Environment getEnvironment() {
if (environment == null) {
throw new RuntimeException("Environment has not been set yet");
}
return environment;
}
}
如果您既不希望使用@Autowire,也不希望注入@Value,您可以简单地执行以下操作(包括回退):
System.getProperty("spring.profiles.active", "unknown");
Environment
;boolean matchesProfiles(String... profileExpressions)
;@Autowired
private Environment environment;
...
if (env.matchesProfiles("online")) {
...
}
@Service
class ProfileService(
val environment: Environment
) {
fun get(): Profile? {
return Profile[environment.activeProfiles.firstOrNull()]
}
fun isTest(): Boolean {
return get() != Profile.PRD
}
}