使用的场景:开发一套环境,测试一套环境
通过在类中,比如数据源类,加入注解@Profile,其值设为dev(开发)或test(测试),比如
@Bean
@Profile("dev")
public DataSource getDataSource(){
DataSource dataSource;
....//一些获取数据源的操作
return dataSource;
}
@Bean
@Profile("test")
public DataSource getTestDataSource(){
DataSource dataSource;
....//一些获取数据源的操作
return dataSource;
}
xml配置profile
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" profile="dev">
<bean id="dataSource" class="...">
<property name=".." value=".."></property>
</bean>
</beans>
当然也可以配置多个profile
<beans profile="dev">
<bean id="dataSource" class="...">
<property name=".." value=".."></property>
</bean>
</beans>
<beans profile="test">
<bean id="dataTestSource" class="...">
<property name=".." value=".."></property>
</bean>
</beans>
配置完成后如何启动Profile
激活方法:
在使用SpringMvc的情况下可以配置web上下文参数,或者DispatchServlet参数
作为JNDI条目
配置环境变量
配置JVM启动参数
在继承测试环境中使用@ActiveProfile
集成测试环境中使用注解
@RunWith(SpringJunit4ClassRunner.class)
@ContextConfiguration(classes=ProfileConfig.class)
@ActiveProfiles("dev")