5

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?

4

4 回答 4

4

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

于 2012-12-06T09:03:54.950 回答
2

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.

于 2012-12-06T08:30:21.463 回答
1

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.

于 2012-12-06T07:48:19.400 回答
1

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

于 2021-06-05T13:59:43.283 回答