我希望通过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;
}
更新:这个问题是为了获取正在使用的dataSource的引用。以下问题解释了如何以非常简单的方式初始化数据: DataSourceInitializer is not working on Spring boot 1.2
@Autowired private HikariDataSource dataSource;
- Shanerk