概述
在软件开发的过程中,敏捷开发模式很常见,可能是开发人员使用一套环境,而测试人员使用另一套环境,而这两套系统的数据库
是不一样的,在Spring
中我们可以定义Bean的Profile
注解配置
@Component
public class ProfileDataSource{
@Bean("devDataSource")
@Profile("dev")
public DataSource getDevDaraSource(){
...
}
@Bean("testDataSource")
@Profile("test")
public DataSource getTestDaraSource(){
...
}
}
XML配置
<beans profile= "test">
<bean id = "xxx" class = "xxxxx">
....
</bean>
</beans>
<beans profile= "dev">
<bean id = "xxx" class = "xxxxx">
....
</bean>
</beans>
启动Profile
激活Profile的方法有5种:
- 在集成测试环境中使用
@ActiveProfiles
@RunWith(SpringJUnit4ClassRunner. class)
@ContextConfiguration(classes=ProfileConfig.class)
@ActiveProfiles("dev")
public class ProfileTest {
@Autowired
private Data Source dataSource;
@Test
public void test(){
System.out.println(dataSource.getclass().getName());
}
}
- 配置JVM启动参数
spring.profiles.default
:默认启动的Profile
spring.profiles.active
:启动的Profile
,如果配置了它,那么spring.profiles.default
配置项将失效。
JAVA_OPTS="-Dspring.profiles.active=test"
- 配置环境变量
- 作为JNDI 条目
- 在使用
Spring MVC
的情况下可以配置Web上下文参数,或者D ispatchServlet
参数
<!--使用SpringMVC 的DispatcherServlet 环境参数-->
<servlet>
<servlet-name >dispatcher</servlet -name >
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-name>test</param-name>
</init-param>
</servlet>