config.properties
profile=tomcat
重写org.springframework.web.context.ContextLoaderListener的customizeContext方法
public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener {
@Override
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
Resource resource = new ClassPathResource("config.properties");
Properties properties = new Properties();
try {
properties.load(resource.getInputStream());
} catch (IOException e) {
throw new RuntimeException("加载配置文件config.properties失败", e);
}
String profile = properties.getProperty("profile");
if (StringUtils.isBlank(profile)) {
profile = "dev";
}
wac.getEnvironment().setActiveProfiles(profile);
super.customizeContext(sc, wac);
}
}
web.xml
<listener>
<listener-class>com.xxx.ContextLoaderListener</listener-class>
</listener>
代码中使用
@Profile("dev")
@Configuration
public class DevConfig {
......
}