For example, I have
@Service
public class UserSerice {
@Autowired
private HouseService houseService;
}
and
@Service
public class HouseService {
@Autowired
private UserSerice userService;
}
How will Spring autowire this? And is this a good practice to configure beans this way?
Circular dependencies (spring-framework-reference):
For example: Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection...throws a BeanCurrentlyInCreationException.
it is not recommended... One possible solution is to edit the source code of some classes to be configured by setters rather than constructors...
PLUS:
I debugged the circular dependencies in setter way. The sequence seems that:
-> Start to create bean A
-> Start to create bean B
-> Inject A to B, although A is not created fully from perspective of Spring lifecycle
-> Bean B creation finish
-> Inject bean B to A
-> Bean A created
Since it's not a constructor injection, spring can safely instantiate both objects and then satisfy their dependencies. Architecture-wise such case is so called 'code smell'. It's the sign that something is wrong in the composition. Maybe you need to move logic, maybe you need to introduce third class, it depends.
Google for these terms
Flyweight pattern
Circular dependency in java
Just like 2 java objects can refer each other , it is perfectly valid to have such configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With