Let's say we want to use beans A and C created by spring boot. But also we want to create our own bean B that should be initialized in between. The real word scenario is for example: default DataSource, default EntityManagerFactory and customized Flyway service which must run before hibernate. We can easily say flyway should depend on the datasource - @Autowired does the trick. But how can we say that hibernate should depend on our flyway? We can't add anything to the hibernate bean because we don't declare it. So what's the solution? First let's check how and where spring declares the hibernate. After listing *AutoConfiguration classes we see HibernateJpaAutoConfiguration and later, in its superclass, we can find:
@Bean @ConditionalOnMissingBean(name = "entityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory( JpaVendorAdapter jpaVendorAdapter) {...}So one way of enforcing the order is:
@Configuration class FlywayConfig extends HibernateJpaAutoConfiguration { @Autowired Flyway flyway; }And if we need more precise control, we can override the bean:
@Configuration class FlywayConfig extends HibernateJpaAutoConfiguration { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( JpaVendorAdapter jpaVendorAdapter, Flyway flyway) { return super.entityManagerFactory(jpaVendorAdapter); } }Used versions: spring 4.0.3.RELEASE, spring-boot 1.0.2.RELEASE
2 komentarze :
Very helpful, thank you! We were hoping to make use of @AutoConfigureBefore ({ HibernateJpaAutoConfiguration.class }), which didn't do the trick though. We wanted to have a @Configurable hibernate search bridge, but @Inject did not work on the bridge, because the AnnotationBeanConfigurerAspect bean wasn't created at this point in time.
Thank you very much, that was a very helpful hint. I wrote up a few thoughts on the same topic here https://blog.stefanproell.at/2017/03/10/hibernate-search-and-spring-boot/
Post a Comment