From 4cf5c7796d0b96d74f7fc3279358e229eb98244f Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 29 Sep 2023 14:57:40 +0200 Subject: [PATCH] Explicit note on local bean access within @PostConstruct method Closes gh-27876 --- .../core/beans/java/composing-configuration-classes.adoc | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/framework-docs/modules/ROOT/pages/core/beans/java/composing-configuration-classes.adoc b/framework-docs/modules/ROOT/pages/core/beans/java/composing-configuration-classes.adoc index bb919b2af7..638c8736b3 100644 --- a/framework-docs/modules/ROOT/pages/core/beans/java/composing-configuration-classes.adoc +++ b/framework-docs/modules/ROOT/pages/core/beans/java/composing-configuration-classes.adoc @@ -113,7 +113,8 @@ issue, because no compiler is involved, and you can declare When using `@Configuration` classes, the Java compiler places constraints on the configuration model, in that references to other beans must be valid Java syntax. -Fortunately, solving this problem is simple. As xref:core/beans/java/bean-annotation.adoc#beans-java-dependencies[we already discussed], +Fortunately, solving this problem is simple. As +xref:core/beans/java/bean-annotation.adoc#beans-java-dependencies[we already discussed], a `@Bean` method can have an arbitrary number of parameters that describe the bean dependencies. Consider the following more real-world scenario with several `@Configuration` classes, each depending on beans declared in the others: @@ -204,7 +205,6 @@ Kotlin:: ---- ====== - There is another way to achieve the same result. Remember that `@Configuration` classes are ultimately only another bean in the container: This means that they can take advantage of `@Autowired` and `@Value` injection and other features the same as any other bean. @@ -216,6 +216,11 @@ classes are processed quite early during the initialization of the context, and to be injected this way may lead to unexpected early initialization. Whenever possible, resort to parameter-based injection, as in the preceding example. +Avoid access to locally defined beans within a `@PostConstruct` method on the same configuration +class. This effectively leads to a circular reference since non-static `@Bean` methods semantically +require a fully initialized configuration class instance to be called on. With circular references +disallowed (e.g. in Spring Boot 2.6+), this may trigger a `BeanCurrentlyInCreationException`. + Also, be particularly careful with `BeanPostProcessor` and `BeanFactoryPostProcessor` definitions through `@Bean`. Those should usually be declared as `static @Bean` methods, not triggering the instantiation of their containing configuration class. Otherwise, `@Autowired` and `@Value` may not