在系统开发过程中,经常会碰到各种环境问题,其中一种就是,不同的环境需要不同的数据源,不同的环境需要不同的URL,有些是可以通过修改配置文件来做到的。但是当这种切换多的时候,配置起来就容易出错。spring profile 就是个优秀的解决方案。可以根据不同的环境配置不同的bean。
默认情况下bean是不设置环境的,此时spring都会创建,但是那些设置了特殊环境的bean只有在特定环境下才会加载。
一、如何开启spring profile
开启spring profile 需要设置 spring.profiles.default或者spring.profile.active变量的值。若设置了spring.profiles.active的值那么spring 会使用激活的类。若没有设置,那么就使用spring.profiles.default设置的值,激活default的类。
这两个数值有很多设置的方式 任一种都能达到效果。
①设置在web.xml中,作为springMVC的初始化参数
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/spring-mvc.xml
</param-value>
</init-param>
<init-param>
<param-name>spring.profiles.default</param-name>
<param-value>zj</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
②:设置在web.xml中,作为springMVC的初始化参数
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>zj</param-value>
</context-param>
③:JVM参数方式: -Dspring.profiles.active=”zj”
二、设置不同环境下不同的bean
开启spring profile 之后 需要把根据环境变化的对象进行设置。
@Configuration
@ComponentScan
public class ConditionCofig {
@Bean
@Profile("zj")
public WorkService getWindowsService(){
return new WindowsService();
}
@Bean
@Profile("sj")
public WorkService getLinuxService(){
return new LinuxService();
}
}
三、举例
常用举例:
根据环境设置不同的配置文件:
<beans profile="zj" >
<context:property-placeholder location="classpath*:zj.properties" />
</beans>
<beans profile="sj" >
<context:property-placeholder location="classpath*:sj.properties" />
</beans>
设置不同环境良好的避免了 切换环境带来的不变。