Skip to content

Circular reference in JPA, DataSource, initializers #13042

Closed

Description

@dsyer

This was originally reported by a Spring Cloud user (someone trying to upgrade the Petclinic microservice edition to Spring Boot 2.0 - so it works with 1.5): spring-cloud/spring-cloud-commons#355.

I'm still a bit mystified as to why it happens, but the evidence is pointing to something in the DataSourceInitializer and its configuration (there's a BeanPostProcessor that forcibly instantiates the DataSourceInitializerInvoker when it sees a DataSource).

Here's a really small app that blows up in the same way (with no Spring Cloud dependencies). You need a schema.sql and a data.sql to make it fail, and you need to set spring.datasource.initialization-mode=embedded (or always) to trigger the initialization. Dependencies are just h2 and the JPA starter.

@SpringBootApplication
public class BeanApplication {

	@Bean
	public static BeanFactoryPostProcessor fooScope() {
		return beanFactory -> {
			beanFactory.registerScope("foo", new SimpleThreadScope());
		};
	}

	@Bean
	@Scope("foo")
	@ConfigurationProperties(prefix = "spring.datasource.hikari")
	public HikariDataSource dataSource(DataSourceProperties properties) {
		HikariDataSource dataSource = properties.initializeDataSourceBuilder()
				.type(HikariDataSource.class).build();
		return dataSource;
	}

	public static void main(String[] args) {
		SpringApplication.run(BeanApplication.class, args);
	}

}

If you (exclude= {HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class}) the problem goes away. Here's some code in github: https://github.com/scratches/datasource-cycle.

While I was investigating the Cloud issue I also managed to find some combinations of auto configurations that led to other cycles (not involving JPA, but still with a scoped data source), so there is more than one way to tickle this.

Activity

  1. snicoll commented on May 3, 2018

    @snicoll
    Member

    there's a BeanPostProcessor that forcibly instantiates the DataSourceInitializerInvoker when it sees a DataSource

    There is one in 1.5.x as well si I am not sure how that's relevant to the description.

    I guess we need to figure out what has changed with regards to the scope thing.

  2. dsyer commented on May 3, 2018

    @dsyer
    MemberAuthor

    This fails with 1.5 (in a different way):

    @SpringBootApplication
    public class BeanApplication {
    
    	@Bean
    	public static BeanFactoryPostProcessor fooScope() {
    		return beanFactory -> {
    			beanFactory.registerScope("foo", new SimpleThreadScope());
    		};
    	}
    
    	@Bean
    	@Scope("foo")
    	@ConfigurationProperties(prefix = "spring.datasource")
    	public DataSource dataSource(DataSourceProperties properties) {
    		return DataSourceBuilder.create().url(properties.determineUrl())
    				.type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
    	}
    
    	public static void main(String[] args) {
    		SpringApplication.run(BeanApplication.class, args);
    	}
    
    }

    It's on a branch 1.5.x in the same repo.

  3. self-assigned this
    on May 3, 2018
  4. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    The 1.5.x version fails because the DataSourceInitializer ends up with this.dataSource being null. This happens because this.applicationContext.getBeanNamesForType(DataSource.class, false, false) returns an empty array. The array is empty because the dataSource bean definition doesn't match. The bean definition doesn't match because it's scoped which causes org.springframework.beans.factory.support.AbstractBeanFactory.isSingleton(String) to return false. This matters because of this logic in Framework.

    As far as I can tell, there's no circular reference problem in this case. The problem is that calling this.applicationContext.getBeanNamesForType(DataSource.class, false, false), as DataSourceInitializer does, will never be able to find a DataSource that's in a scope. You can see this by removing the data.sql and schema.sql scripts from the 1.5.x branch of the sample and changing its main method to the following:

    public static void main(String[] args) {
        String[] dataSources = SpringApplication.run(BeanApplication.class, args).getBeanNamesForType(DataSource.class, false, false);
        System.out.println(Arrays.toString(dataSources));
    }

    It will output an empty array.

  5. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    The 2.0.x version fails because of a difference in how singleton beans and prototype beans are handled when they are requested while still be created. In the singleton case, there's some fallback logic that allows the singleton that's in creation to be retrieved. In the prototype case, there's no such fallback and a BeanCurrentlyInCreationException is thrown.

  6. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    In SPR-16783, @jhoeller said that "the recommendation is to never access an object within its own post-processing phase to begin with". This is exactly what DataSourceInitializerPostProcessor does when it gets the DataSourceInitializer (1.5) or DataSourceInitializerInvoker (2.0) beans. Putting aside Framework's inconsistent handling of retrieving a singleton that's in creation vs retrieving a prototype that's in creation, we probably need to find another approach anyway.

  7. dsyer commented on May 3, 2018

    @dsyer
    MemberAuthor

    The "singleton" in question isn't the same as the default scope for beans (I think). It's "raw" singletons (the ones that are registered directly as instances, not bean definitions). The DataSource isn't in that category. I'm not sure how that helps, though.

  8. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    The "singleton" in question isn't the same as the default scope for beans (I think). It's "raw" singletons (the ones that are registered directly as instances, not bean definitions).

    I'm pretty sure it's the same. When I remove the @Scope and step through this code, the dataSource bean is marked as being in creation but it's still accessible.

  9. dsyer commented on May 3, 2018

    @dsyer
    MemberAuthor

    OK, maybe the raw singletons get cached in the same place as the bean definition ones.

    I added some non-hibernate samples to my repro project, here: https://github.com/scratches/datasource-cycle/tree/master/src/main/java/org/springframework/boot/autoconfigure/jdbc. They are easier to analyse (fewer beans), but the exception is slightly different.

  10. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    I added some non-hibernate samples to my repro project

    Thanks. BrokenApplication exhibits the same problem as I described above, failing because the dataSource prototype is in creation when an attempt is made to retrieve it.

    I'm intrigued by the other two as they look like they should fail in the same way. Time to do some digging.

  11. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    NotBrokenApplication is not broken because of an ordering change in the configuration (DataSourceInitializationConfiguration going before DataSourceJmxConfiguration). This ordering change means that afterPropertiesSet on DataSourceInitializerInvoker is called outside of the post-processing of the DataSource. This means that the attempt to retrieve the DataSource while it's being created is avoided.

  12. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    AnotherNotBrokenApplication appears to not be broken for the same reason as NotBrokenApplication. Updating the ordering of the imported configuration classes so that DataSourceJmxConfiguration goes before DataSourceInitializationConfiguration causes it to fail due to a cycle.

  13. wilkinsona commented on May 3, 2018

    @wilkinsona
    Member

    When the 2.0.x version of BeanApplication fails, it does so because the early retrieval of LoadTimeWeaverAware beans has triggered the creation and post-processing of the DataSource bean before DataSourceInitializerInvoker has been created because the LocalContainerEntityManagerFactoryBean is load time weaver-aware and depends on the DataSource. This leads to DataSourceInitializerInvoker bean created during the post-processing of the DataSource bean.

    The problem can be avoided by making DataSourceInitializerInvoker implement LoadTimeWeaverAware. Due to auto-configuration ordering, it's defined before the definition of the LocalContainerEntityManagerFactoryBean so, if it's LoadTimeWeaverAware, it's created and initialised first which allows it to retrieve the DataSource when it isn't already under creation.

  14. spencergibb commented on May 3, 2018

    @spencergibb
    Member

    Thanks for all the research @wilkinsona and @dsyer

  15. 34 remaining items

  16. klopfdreh commented on May 31, 2019

    @klopfdreh

    @wilkinsona - no spring cloud, but spring-boot 2.1.x, but there the actuator endpoint is also affected. Could be that this is a project related issue. If I have more information I can share I am going to do so.

  17. wilkinsona commented on May 31, 2019

    @wilkinsona
    Member

    Thanks. Are you doing anything with your own custom scopes or prototype beans? IIRC, the various examples listed above all require one or the other for the problem to occur. You may be facing the same problem as described in this issue, or it may be something else. We've yet to see Actuator be the cause of the problem and I suspect it's not in your case and that what you're seeing is just a symptom.

    Unfortunately, we won't be able to do any more than speculate without having some code to look at so fingers-crossed that you're able to share something. It doesn't have to be your exact code, just enough to reproduce the problem that you're seeing.

  18. klopfdreh commented on May 31, 2019

    @klopfdreh

    I just tried to update to spring-boot 2.1.5 but facing the same error.

    I just had a look in the initialization of the custom DataSource bean. The bean itself is created within a class using @Bean and checking against the same bean name (method name) with @ConditionalOnMissingBean. The class itself is a @Configuration with @ConditionalOnProperty.

    In this case I guess the default scope is used (singleton) and it is not a prototype bean.

    All in all there is no specific scope handling introduced.

    I know that you can't do anything more without stacktrace, but I just wanted to provide those information about the actuator endpoint and that this is not only occuring in spring-cloud.

    This is only an assumption, but is there any specific handling for datasources in kind of bean creation? This error seems to occure only with an additional DataSource provided as bean and in this particular scenario with the actuator endpoint, because @samo-esure also mentioned to change the managament port works (this also worked for me) - also the spring-cloud issue listed this in the stack. Also to disable the health endpoint or the db indicator worked.

    So I assume that this is an issue around the DataSource injection within the actuator implementation or an issue related to the startup of this spring module.

  19. klopfdreh commented on May 31, 2019

    @klopfdreh

    @wilkinsona - We found the issue and it is really hard to explain in detail. Basically it was an issue that the health endpoint was causing the DataSource bean to be created way earlier than without. Because of that shift in the order of the bean creation the configuration class in which the datasource was created was invoked a bit earlier and a setter (also autowired with required false) was resolved. Finally this setter was causing the circular dependency.

    So the error was missleading and might also misslead in other scenarios to the assumption that the actuator health endpoint is the issue.

    So my advice would be to ask devs facing this issue - for those who not defined custom scopes - to have a look in the context at which a custom datasource is created and search for circular dependencies in that area (especially with optional beans).

  20. removed their assignment
    on Jul 16, 2019
  21. jebeaudet commented on Jun 12, 2020

    @jebeaudet
    Contributor

    We just ran into this while trying to use org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource with some custom logic to which datasource each query will hit. I've put up a small sample here.

    There are 2 configurations classes, ActualConditionsWeRanInto and DeadSimpleReproducingConditions, just enable any one of them to reproduce the problem.

    The key here I believe is the @Primary annotation, the DataSourceInitializerInvoker gets invoked on the first DataSource created (not the primary one) and tries to create the primary instance in the ObjectProvider<Datasource>#getIfUnique method invocation, creating the cycle.

    Our fix for now is to disable the DataSourceAutoConfiguration class but I'd rather avoid that, anything else we could do? We don't use initialization and the spring.datasource.initializationMode property gets checked after the problem so setting it to NEVER has no impact.

  22. modified the milestones: 2.x, 2.5.x on Feb 17, 2021
  23. self-assigned this
    on Feb 17, 2021
  24. modified the milestones: 2.5.x, 2.5.0-M2 on Feb 17, 2021
  25. wilkinsona commented on Feb 17, 2021

    @wilkinsona
    Member

    This is noteworthy as the release notes should mention the new spring.datasource.initialization-order that controls whether initialization is performed before or after JPA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

for: upgrade-attentionAn issue requiring extra attention when upgradingtype: bugA general bug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions