我需要根据当前不同的环境概要文件编写不同的逻辑。

如何从Spring获得当前活动的和默认的概要文件?


当前回答

您可以自动装配环境

@Autowired
Environment env;

环境提供了:

String [] getActiveProfiles (), String[] getDefaultProfiles(), and 布尔acceptsProfiles(字符串…配置文件)

其他回答

如前所述。您可以自动装配环境:

@Autowired
private Environment environment;

只有你可以更容易地检查所需的环境:

if (environment.acceptsProfiles(Profiles.of("test"))) {
    doStuffForTestEnv();
} else {
    doStuffForOtherProfiles();
}
@Value("${spring.profiles.active}")
private String activeProfile;

它可以工作,而且你不需要实现EnvironmentAware。但我不知道这种方法有什么缺点。

如果你既不想使用@Autowire也不想注入@Value,你可以简单地这样做(包括回退):

System.getProperty("spring.profiles.active", "unknown");

这将返回任何活动的配置文件(或回退到'unknown')。

您可以自动装配环境

@Autowired
Environment env;

环境提供了:

String [] getActiveProfiles (), String[] getDefaultProfiles(), and 布尔acceptsProfiles(字符串…配置文件)

如果不使用自动装配,只需实现EnvironmentAware