如何将 Spring DataSourceInitializer 同时与 @Primary 和辅助 DataSource bean 一起使用?

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

我有一个场景,我想要一个 @Primary DataSource bean 依赖于另一个 DataSource bean。我在执行此操作时遇到了 BeanCurrentlyInCreationException 异常,因为 DataSourceInitializer@Primary bean 仍在创建时触发了它的解析。

我创建了一个示例存储库来重现此问题并对其进行更详细的解释(如果有帮助的话):https://github.com/zachmarshall/spring-datasource-init-bug

A Spring Boot issue 就是为此创建的。承认代码至少有问题,但还没有真正的解决方案。

最终,我确实找到了 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.