Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Spring 3+ autowire beans, which 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 autowire this? And is this a good practice to configure beans this way?

like image 719
Mikhail Kopylov Avatar asked Dec 06 '12 07:12

Mikhail Kopylov


3 Answers

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

like image 178
卢声远 Shengyuan Lu Avatar answered Oct 23 '22 11:10

卢声远 Shengyuan Lu


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.

like image 33
xeye Avatar answered Oct 23 '22 10:10

xeye


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.

like image 33
Subin Sebastian Avatar answered Oct 23 '22 10:10

Subin Sebastian