在企业开发的过程中,项目往往要面临开发环境、测试环境、准生产环境和生产环境的切换,每一套的上下文是不一样的,它们有各自的数据库资源
Profile机制:实现各个环境之间的切换。
假设存在dev_spring_boot和test_spring_boot两个数据库,这样可以使用注解**@Profile**定义两个Bean:
@Bean(name = "dataSource", destroyMethod = "close")
@Profile("dev")
public DataSource getDevDataSource() {
Properties props = new Properties();
props.setProperty("driver", "com.mysql.jdbc.Driver");
props.setProperty("url", "jdbc:mysql://localhost:3306/dev_spring_boot");
props.setProperty("username", "root");
props.setProperty("password", "123456");
DataSource dataSource = null;
try {
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean(name = "dataSource", destroyMethod = "close")
@Profile("test")
public DataSource getTestDataSource() {
Properties props = new Properties();
props.setProperty("driver", "com.mysql.jdbc.Driver");
props.setProperty("url", "jdbc:mysql://localhost:3306/test_spring_boot");
props.setProperty("username", "root");
props.setProperty("password", "123456");
DataSource dataSource = null;
try {
dataSource = BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
在Spring中存在两个参数以修改启动Profile机制,两个属性都没有配置的情况下,Spring将不会启动Profile机制,即被@Profile标注的Bean将不会被Spring装配到IoC容器中:
一个是spring.profiles.active,
一个是spring.profiles.default。
两个属性存在优先级,先判定是否存在spring.profiles.active配置后,再去查找spring.profiles.default配置的
通过这个配置就能启动Profile机制,指定环境
JAVA_OPTS="-Dspring.profiles.active=dev"
将日志的配置级别改为DEBUG,会有很详细的日志显示
logging.level.root=debug
logging.level.org.springframework=debug