How can I create a Spring boot project with multiple data sources?

I am working on a Spring Boot / Spring Batch project, and I need to configure two data sources. One of them is the in-memory hsqldb database, used to track transactions. The other is the regular MySQL database, which will be updated by my ItemWriters.

The problem is that as soon as I try to configure the second data source, Spring starts throwing unsolvable cyclic dependency errors, i.e.

Error creating bean with name 'preprodDataSource' defined in class path 
resource [xxx/tools/batch/xxx/MyConfiguration.class]: Initialization of
bean failed; nested exception is 
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error 
creating bean with name 'dataSourceAutoConfigurationInitializer': Requested bean is 
currently in creation: Is there an unresolvable circular reference?

The corresponding fragment of my MyConfiguration.java file looks like this:

@Bean
public DataSource transactionsDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:testdb;sql.enforce_strict_size=true;hsqldb.tx=mvcc");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    return dataSource;
}

@Bean
public DataSource preprodDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/somedb");
    dataSource.setUsername("someuser");
    dataSource.setPassword("somepass");
    return dataSource;
}

If I comment on @ Bean defining a second data source, everything is fine. The application starts and runs without problems. However, if I leave it, I get the error above.

, Spring 'dataSourceAutoConfigurationInitializer' , , .

?

+4
1

, Spring JdbcTemplate DataSource. , , . , , @Primary:

@Bean
@Primary
public DataSource transactionsDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    return dataSource;
}

.

+2

Source: https://habr.com/ru/post/1548701/


All Articles