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注解配置。