Get a reference to currently active dataSource in Spring Boot

developer10 picture developer10 · Mar 31, 2017 · Viewed 28.4k times · Source

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

Answer

Essex Boy picture Essex Boy · Mar 31, 2017

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

@Autowired
DataSource dataSource;

Should do it.