在春季创建后如何使用数据源配置文件

时间:2019-05-09 14:24:49

标签: spring

我知道如何使用配置文件配置多个数据源,但是如何使用特定的数据源。假设在开发中我想使用开发概要文件数据源,而在生产中,我想使用生产概要文件数据源。下面是具有多个配置文件配置的代码,但是如何激活特定配置文件并使用它。

@Configuration
public class DataSourceConfiguration {
@Profile("development")
@Bean
public DataSource embeddedDataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql")
.addScript("classpath:test-data.sql")
.build();
}
@Profile("qa")
@Bean
public DataSource Data() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:tcp://localhost/~/spitter");
ds.setUsername("sa");
ds.setPassword("");
ds.setInitialSize(5);
ds.setMaxActive(10);
return ds;
}
@Profile("production")
@Bean
public DataSource dataSource() {
JndiObjectFactoryBean jndiObjectFactoryBean
= new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName("jdbc/SpittrDS");
jndiObjectFactoryBean.setResourceRef(true);
jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
return (DataSource) jndiObjectFactoryBean.getObject();
}
}

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用参数启动应用程序:

-Dspring.profiles.active=dev

更多信息在这里: https://www.baeldung.com/spring-profiles