SSM-Spring-Spring装配Bean-装配混合使用-使用Profile
解决在不同环境中进行切换的需求,如开发人员与测试人员使用两套不一样的环境
使用注解@Profile配置
使用@Profile配置两个数据库连接池,一个用于开发,一个用于测试
@Component
public class ProfileDataSource {
//开发环境
@Bean(name="devDataSource")
@Profile("dev")
public DataSource getDevDataSource(){
Properties props=new Properties();
props.setProperty("driver","com.mysql.jdbc.Driver");
props.setProperty("url","jdbc:mysql://localhost:3306/chapterl2");
props.setProperty("username","root");
props.setProperty("password","123456789");
DataSource dataSource=null;
try{
dataSource=BasicDataSourceFactory..createDataSource(props)
}catch (Exception e){
e.printStackTrace() ;
}
return dataSource;
}
//测试环境
@Bean(name="testDataSource")
@Profile("test")
public DataSource getDevDataSource(){
Properties props=new Properties();
props.setProperty("driver","com.mysql.jdbc.Driver");
props.setProperty("url","jdbc:mysql://localhost:3306/chapterl2");
props.setProperty("username","root");
props.setProperty("password","123456789");
DataSource dataSource=null;
try{
dataSource=BasicDataSourceFactory..createDataSource(props)
}catch (Exception e){
e.printStackTrace() ;
}
return dataSource;
}
}
使用XML定义Profile
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/beans/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<beans profile="dev">
<bean id="devDataSource" class="org.apache.commons.dbcp2.BasicDataSourceFactory">
<property name="driverClassName" value="xxx"></property>
<property name="url" value="xxx"></property>
<property name="username" value="xxx"></property>
<property name="password" value="xxx"></property>
</bean>
</beans>
<beans profile="test">
<bean id="devDataSource" class="org.apache.commons.dbcp2.BasicDataSourceFactory">
<property name="driverClassName" value="xxx"></property>
<property name="url" value="xxx"></property>
<property name="username" value="xxx"></property>
<property name="password" value="xxx"></property>
</bean>
</beans>
</beans>
启动profile
当启动java配置或者XML配置Profile时,可以发现这两个Bean并不会加载到Spring IOC容器中,需要自行激活profile,有五种方法激活:
- 在使用Spring MVC的情况下可以配置Web上下文参数,或者DispatchServlet参数
- 作为JNDI条目
- 配置环境变量
- 配置JVM启动参数
- 在集成测试环境中使用@ActiveProfiles