获取对 Spring Boot 中当前活动数据源的引用
2022-09-01 15:21:45
我想通过 实现 db data init。DataSourceInitializer
我把它们作为方法放在我的Spring Boot主方法下面,但它似乎根本没有被执行(我尝试故意删除字符只是为了触发一个错误,这将确认执行。什么也没发生)。
@ConfigurationProperties(prefix="spring.datasource")
@Bean
public DataSource getDataSource() {
// i was hoping this was going to pull my current datasource, as
// defined in application.properties
return DataSourceBuilder
.create()
.build();
}
@Bean
public DataSourceInitializer dataSourceInitializer() {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("/data/init/initData.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
// the call to the above method
dataSourceInitializer.setDataSource(getDataSource());
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
更新:此问题旨在获取对正在使用的数据源的引用。这个问题解释了如何以非常简单的方式初始化数据:DataSourceInitializer在Spring boot 1.2上不起作用