spring的指定profile

40 阅读1分钟

前言

源码xsd文件已经说的很明白,beans标签的profile属性设置了,就会将它之下所有bean归为这一属性文件,可以用逗号、空格、分号指定多个profile<beans profile="dev,test"> 只有对应属性文件处于激活状态,才会解析注册对应的bean定义,否则不会解析。xml中可以用!前缀不激活属性。

设置profile

xml

<beans profile="dev">
    <bean ...></bean>
</beans>

注解

@Profile("dev")放在配置类上,也可以和单个@Bean一起放在定义bean的方法上

激活profile

web.xml中激活,这属于servlet上下文中初始化

 context-param>
   <param-name>spring.profiles.active</param-name>
   <param-value>dev</param-value>
 </context-param>

.properties文件激活,这同样属于于servlet上下文激活

spring.profiles.active = p1, p2
//default指定的默认激活文件,但如果指定了active,那么默认将被active覆盖
spring.profiles.default = p1, p2

JVM参数设置环境变量java -Dspring.profiles.active=dev

硬编码激活

//设置环境变量
System.setProperty("spring.profiles.active", "dev,test");
//sring内置设置方法
ConfigurableEnvironment # setActiveProfiles (String…)
ConfigurableEnvironment # setDefaultProfiles (String…)
最终是这样调用
context.getEnvironment().setActiveProfiles("dev", "test");

硬编码激活

一定要在bean定义加载注册前激活。也就是在refresh之前。例如xml非web应用,就不能之际通过构造函数创建上下文,而是先构建上下文对象,关闭refersh,避免无谓的刷新,激活profile后再设置配置文件,最后refresh

// 创建 ApplicationContext 但不立即刷新(refresh=false) 
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(false); // 获取环境对象并设置激活的 Profile
context.getEnvironment().setActiveProfiles("dev"); // 设置配置文件位置并刷新 
context.setConfigLocation("newtype.xml"); 
context.refresh();