Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a reference to currently active dataSource in Spring Boot

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

like image 658
developer10 Avatar asked Mar 31 '17 14:03

developer10


People also ask

How do I get existing datasource in spring boot?

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.

What is Springsource data boot?

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.

How do I set different datasources in spring boot?

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: ...


1 Answers

If you have a datasource already created it will be in the spring container, so:

@Autowired DataSource dataSource; 

Should do it.

like image 55
Essex Boy Avatar answered Sep 18 '22 15:09

Essex Boy