I want to implement db data init via DataSourceInitializer
.
I have these as methods just below my Spring Boot main method, but it seems that it doesn't get executed at all (I tried with intentional removal of characters just to trigger an error which would confirm the execution. Nothing happened.):
@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; }
UPDATE: This question was aimed at getting a reference to the dataSource in use. This question explains how to init the data in a very simple way: DataSourceInitializer is not working on Spring boot 1.2
To access the Relational Database by using JdbcTemplate in Spring Boot application, we need to add the Spring Boot Starter JDBC dependency in our build configuration file. Then, if you @Autowired the JdbcTemplate class, Spring Boot automatically connects the Database and sets the Datasource for the JdbcTemplate object.
Spring boot datasource configuration is nothing but the factory of connection which was used in a physical data source. Spring boot datasource uses the database credential to set up connections between the database server, it is alternative to the facility of Driver Manager.
So, to use multiple data sources, we need to declare multiple beans with different mappings within Spring's application context. The configuration for the data sources must look like this: spring: datasource: todos: url: ... username: ...
If you have a datasource already created it will be in the spring container, so:
@Autowired DataSource dataSource;
Should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With