Referencing a @Bean method in a @Configuration class' @PostConstruct method leads to circular reference
See original GitHub issueAfter upgrading to spring-boot 2.6.x, it is no longer possible to access a bean in the @PostConstruct
method of the @Configuration
class where it was defined. This did work before (tested with 2.1.x, 2.5.6).
Example code that will result in a BeanCurrentlyInCreationException
, printing “Application Failed to start”, with “The dependencies of some of the beans in the application context form a cycle:”
@Configuration
public class AppConf {
@Bean
public String getTestBean() {
return "";
}
@PostConstruct
public void init() {
getTestBean();
}
}
You can get a full example at https://github.com/BartRobeyns/boot26ConfigPostConstruct (spring-initializer project with only the @Configuration
class above added) that fails to build.
Changing the spring-boot version to 2.5.x will allow the application to build and run.
Note that I’m totally fine with this behavior (@PostConstruct
in a @Configuration
class seems pretty weird to me), but the documentation of @PostConstruct
does state that the
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This annotation must be supported on all classes that support dependency injection.
… so it’s easy to expect the sample above to work. An explicit mention that you shouldn’t access @Bean
methods from the @Configuration
class itself would clear that up.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:13 (5 by maintainers)
@snicoll that clarifies the release notes for me, thanks. I still think that an extra warning in the documentation that you shouldn’t access @Bean methods from the @Configuration class itself would help users that are puzzled by the circular reference error mentioning only the @Configuration class; it’s difficult for a user to understand how that @Configuration class can have an invalid circular reference to itself. (But feel free to close this ticket without further action if you disagree)
Added to triage queue as there is some change in behavior, possibly requiring a small documentation update/clarification?