Spring中激活profile的方法:设置spring.profiles.active和spring.profiles.default这两个属性
设置激活profile属性的地方(优先级由高到底)
0)Spring上下文
ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(EnvironmentApp.class);
ConfigurableEnvironment env = ctx.getEnvironment();
或
ApplicationContext ctx = new AnnotationConfigApplicationContext(EnvironmentApp.class);
Environment _e =ctx.getEnvironment();
ConfigurableEnvironment env = ConfigurableEnvironment.class.cast(_e);
//通过setActiveProfiles来设置。
env.setActiveProfiles("wow","pes","ff");
//必须重建容器
ctx.refresh();
1)ServletConfig parameters(if applicable, e.g. in case of a DispatcherServlet context)
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</init-param>
2)ServletContext parameters(web.xml context-param entries)
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
3)JNDI environment variables
4)JVM system properties
JVM system properties的设置方式
a) 设置JVM的启动参数 -D<name>=<value> ("-D" command-line arguments)
i) 在tomcat内的catalina.bat(.sh中不用"set")中加 JAVA_OPTS="-Dspring.profiles.active=dev"
ii) eclipse中设置run configuration:-Dspring.profiles.active=dev
JVM启动参数, refer to https://blog.csdn.net/lsziri/article/details/81200334 ; https://www.cnblogs.com/flashsun/p/7246232.html
b) JAVA标准API:
System.setProperty("spring.profiles.active", "dev");//在启动容器之前,先指定环境中的profiles参数
ApplicationContext ctx = new AnnotationConfigApplicationContext(EnvironmentApp.class);
5)OS environment variable
增加环境变量,eg.spring.profiles.active=dev
读取配置文件 <context:property-placeholder location="classpath:config_${spring.profiles.active}.properties" ignore-unresolvable="true" />
JNDI environment variables ("java:comp/env/" entries)
在集成测试类上,使用@ActiveProfiles注解配置。