从配置文件中初始化spring profile

来源:互联网 发布:java转义代码 编辑:程序博客网 时间:2024/06/10 22:19

config.properties

profile=tomcat


重写org.springframework.web.context.ContextLoaderListener的customizeContext方法

public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener {@Overrideprotected 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 {      ......  } 


0 0
原创粉丝点击