Mikhail Kopylov
Mikhail Kopylov

Reputation: 2058

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?

Upvotes: 6

Views: 5013

Answers (4)

AITAALI_ABDERRAHMANE
AITAALI_ABDERRAHMANE

Reputation: 2519

Keep calm and use @Lazy

you can break the circular dependency using the @Lazy annotation()

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

you can use the HouseService as it is (no change :) )

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

further solutions : https://www.baeldung.com/circular-dependencies-in-spring#2-use-lazy

Upvotes: 1

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

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

Upvotes: 4

xeye
xeye

Reputation: 1256

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.

Upvotes: 2

Subin Sebastian
Subin Sebastian

Reputation: 10997

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.

Upvotes: 1

Related Questions