Skip to content

Commit b59a50f

Browse files
Document @lazy and ObjectProvider remedies for circular dependencies
Expand the "Circular dependencies" callout to recommend refactoring away the cycle and to describe keeping constructor injection via @lazy on a constructor parameter or an ObjectProvider/Provider for on-demand lookup, in addition to the existing setter-injection fallback. See gh-26703
1 parent 99b991b commit b59a50f

1 file changed

Lines changed: 19 additions & 4 deletions

File tree

framework-docs/modules/ROOT/pages/core/beans/dependencies/factory-collaborators.adoc

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,25 @@ beans for classes A and B to be injected into each other, the Spring IoC contain
377377
detects this circular reference at runtime, and throws a
378378
`BeanCurrentlyInCreationException`.
379379
380-
One possible solution is to edit the source code of some classes to be configured by
381-
setters rather than constructors. Alternatively, avoid constructor injection and use
382-
setter injection only. In other words, although it is not recommended, you can configure
383-
circular dependencies with setter injection.
380+
A circular dependency is often a sign that responsibilities are not cleanly separated.
381+
The preferred solution is therefore to refactor the design so that the cycle is removed --
382+
for example, by extracting the shared logic into a third collaborator that both beans
383+
depend on.
384+
385+
If the cycle cannot be avoided, you have a few options for keeping constructor injection:
386+
387+
* Annotate one of the constructor parameters with
388+
xref:core/beans/dependencies/factory-lazy-init.adoc[`@Lazy`]. Spring then injects a lazy-resolution
389+
proxy for that dependency instead of the fully initialized bean, deferring the actual
390+
lookup until the dependency is first used and thereby breaking the cycle.
391+
* Inject an
392+
xref:core/beans/annotation-config/autowired.adoc[`ObjectProvider<T>`] (or `Provider<T>`) for one side of
393+
the cycle and retrieve the collaborating bean on demand rather than at construction time.
394+
395+
Alternatively, you can edit the source code of some classes to be configured by
396+
setters rather than constructors, or avoid constructor injection and use setter injection
397+
only. In other words, although it is not recommended, you can configure circular
398+
dependencies with setter injection.
384399
385400
Unlike the typical case (with no circular dependencies), a circular dependency
386401
between bean A and bean B forces one of the beans to be injected into the other prior to

0 commit comments

Comments
 (0)