navigation
1. What is circular dependency?
Circular dependency refers to the situation where two or more modules have mutual dependencies and calls, resulting in the inability of these modules to compile and run independently.
1.1 Interdependence
Interdependence is the most common dependency error problem in development. When interdependence occurs, an error as shown in the figure will be automatically reported at startup:
This is a problem encountered during the development process, and as shown in the figure As shown here, slDispatchingServiceImpl depends on slStoreOutWorkServiceImpl, and slStoreOutWorkServiceImpl depends on slDispatchingServiceImpl, which leads to an interdependence problem.
1.2 Dependence among the three
This means that A depends on B, B depends on C, and C depends on A. As a result, although there is no circular dependency problem between the two, the three are actually dependent on each other.
1.3 Self-reliance
This means A depends on A
2. Solution
2.1 Analysis
Spring actually designed a three-level cache to solve the circular dependency problem. When we call getBean(), spring will first find the target bean from the first-level cache. If it is not found, it will search for it in the second-level cache. It has not been found yet. It means that the target bean has not been instantiated, so spring will instantiate the target bean. If there is no circular dependency, the bean will be placed in the second-level cache (early bean). Otherwise, the bean will be marked as having a circular dependency and wait for the next round. Query assignment, that is, parse Autowired annotations. After the annotation assignment is completed, the target is stored in the first-level cache.
2.2 Plan
Judging from the picture above, it is actually obvious that the error is caused by the mutual dependence of the two service layers. Then take a look at the two service layers. At first glance, oh, it is indeed dependent. At this time, we can modify a
certain service to solve the problem of interdependence. For example, I solved the problem of circular dependency by downgrading the service to a mapper.
@Resource
private SlDispatchingMapper dispatchingMapper;