[Solved] springboot Startup Error: Bean with name ‘xxxxService‘ has been injected into other beans

An error was reported when starting the project in the local test today:

Bean with name ‘commonService’ has been injected into other beans [] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching – consider using ‘getBeanNamesOfType’ with the ‘allowEagerInit’ flag turned off, for example.**

Reason for error reporting:
it depends on a loop. Now I have a method that ServiceA needs to call serviceb, so ServiceA depends on serviceb, and there is a method that calls ServiceA in serviceb, which forms a loop dependency. When spring initializes a bean, it does not know which bean to initialize first, and an error will be reported.

What is circular dependency
bean a depends on B, and bean B depends on A. in this case, circular dependency occurs
bean a → bean B → bean a
more complex indirect dependencies cause cyclic dependencies as follows
Bean A → Bean B → Bean C → Bean D → Bean E → Bean A

What are the consequences of circular dependencies
when spring is loading all beans, spring tries to create beans in the order that they can be created normally
for example, there are the following dependencies:
bean a → bean B → bean C
spring first creates bean C, then creates bean B (injects C into b), and finally creates bean a (injects B into a).

However, when there is a circular dependency, spring will not be able to decide which bean to create first. In this case, spring will generate the exception beancurrentyincreationexception.

1. Refactor the code and decouple it
2. When injecting beans, add @lazy annotation on the two interdependent beans

Similar Posts: