How are Spring 3+ autowire beans that use each other?

For example, I have

@Service public class UserSerice { @Autowired private HouseService houseService; } 

and

 @Service public class HouseService { @Autowired private UserSerice userService; } 

How will Spring auto-install this? And is it good to configure beans this way?

+4
source share
3 answers

Since this is not a constructor injection, spring can safely instantiate both objects and then satisfy their dependencies. An architecturally similar case is called the so-called "code smell." This is a sign that something is wrong with the composition. Maybe you need to move the logic, maybe you need to introduce a third class, it depends.

+2
source

Circular dependencies (spring-framework-reference):

For example: class A requires an instance of class B through the constructor injector, and class B requires an instance of class A through constructor injection ... throws a BeanCurrentlyInCreationException.

Not recommended. . One possible solution is to edit the source code of some classes configured by setters, rather than constructors ...

PLUS:

I debugged cyclic dependencies in the installation method. the sequence seems to be:

-> Start creating bean A

-> Start creating bean B

-> Insert A into B, although A is not created entirely from the Spring perspective of the life cycle

-> bean Finish B

-> Enter bean B in A

-> bean Created

+3
source

Google for these conditions

Weight figure

Circular dependency in java

Just as 2 java objects can refer to each other, it is perfectly acceptable to have such a configuration.

+1
source

All Articles