项目开发一共有三个环境:测试环境,灰度环境和生产环境,好比咱们想在测试环境下,不加载某些配置信息,能够经过profile来实现spring
JVM增长参数spring.profiles.active设置缓存
在ServletContextListener 中初始化属性spring.profiles.activetomcat
在JVM中增长参数spring.profiles.active设置,若是咱们想设置spring.profiles.active为dev,使用Dspring.profiles.active="dev" 。springboot
此种方式须要修改tomcat的JVM配置,通用性不高。mybatis
写一个类InitConfigListener实现接口ServletContextListener,重写容器初始化方法contextInitialized(),设置属性为spring.profiles.active为指定值environment。
environment能够定义在一个属性文件中,在使用maven构建时使用测试,灰度或者生产环境的属性文件。
在contextInitialized方法中读取指定属性文件,获取environment 值,经过setProperty便可实现。jvm
@WebListener public class InitConfigListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { String environment = ""; //加载Properties属性文件获取environment值 //侦测jvm环境,并缓存到全局变量中 String env = System.setProperty("spring.profiles.active",environment); } @Override public void contextDestroyed(ServletContextEvent sce) { } }
spring.xml配置只在dev模式下加载配置文件spring-mybatis.xmlmaven
<beans profile="dev"> <import resource="spring-mybatis.xml" /> </beans>
springboot使用注解@Profile和@Configuration来配置,@ActiveProfiles()在测试时切换环境ide
你们能够关注个人公众号:不知风在何处,相互沟通,共同进步。测试