根据文档@Profile
注释只能应用于@Component
或@Configuration
。无论如何,您无法在 ContextLoaderListener 中获取有关配置文件的信息,因为尚未加载 ApplicationContext。如果您想在应用程序启动时调用您的代码,我的建议是创建ApplicationListener
并收听ContextRefreshEvent
:
@Component
public class CustomContextListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
Environment environment = contextRefreshedEvent.getApplicationContext().getEnvironment();
if(environment.acceptsProfiles("test")){
System.out.print("Test profile is active");
}
}
}
第一次将在应用程序初始化后调用此侦听器。如果您要在上下文初始化之前获取配置文件信息,您可以创建新的上下文加载器:
public class ProfileContextListener extends ContextLoaderListener {
@Override
public void contextInitialized(ServletContextEvent event) {
if(isProfileActive("test", event.getServletContext())){
System.out.println("Profile is active");
}
}
private boolean isProfileActive(String profileName, ServletContext context) {
String paramName = "spring.profiles.active";
//looking in web.xml
String paramValue = context.getInitParameter(paramName);
if(paramValue==null) {
//if not found looking in -D param
paramValue = System.getProperty(paramName);
};
if(paramValue==null) return false;
String[] activeProfileArray = paramValue.split(",");
for(String activeProfileName : activeProfileArray){
if(activeProfileName.trim().equals(profileName)) return true;
}
return false;
}
}
要激活所需的配置文件,您必须添加到 web.xml 特殊的 spring 环境属性 - spring.profiles.active
:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>default,test</param-value>
</context-param>
或者您可以设置配置文件 throw -D jvm-option
-Dspring.profiles.active=default,test
请注意,您可以添加多个用逗号分隔的配置文件名称。