Search code examples
javaspringspring-bootspring-jdbc

How can you use a Spring DataSourceInitializer with both a @Primary and secondary DataSource bean?


I have a scenario where I'd like to have a @Primary DataSource bean that depends on another DataSource bean. I am currently encountering a BeanCurrentlyInCreationException exception when I do this because the DataSourceInitializer triggers resolution of the @Primary bean while it is still being created.

I've created an example repository that reproduces this issue and explains it in more detail, if helpful: https://github.com/zachmarshall/spring-datasource-init-bug


Solution

  • A Spring Boot issue was created for this. There was acknowledgement that the code is at least problematic, but no real resolution yet.

    Ultimately, I did find a workaround:

    ...by using @DependsOn("dataSourceInitializer") on the @Primary bean definition, spring eagerly creates the dataSourceInitializer bean before the primary is marked as in creation. Kind of a hack but works for now.