Spring解决循环依赖(不讲原理)The dependencies of some of the beans in the application context form a cycle

Spring解决循环依赖(不讲原理)The dependencies of some of the beans in the application context form a cycle,第1张

Spring解决循环依赖(不讲原理)The dependencies of some of the beans in the application context form a cycle 循环依赖场景

有三个类:

@Service
public class AService {
    @Autowired
    private BService bService;
}

@Service
public class BService {
    @Autowired
    private CService cService;
}

@Service
public class CService {
    @Autowired
    private AService aService;
}

造成循环依赖报错:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  AService (field private com.example.demo.service.BService com.example.demo.service.AService.bService)
↑     ↓
|  BService (field private com.example.demo.service.CService com.example.demo.service.BService.cService)
↑     ↓
|  CService (field private com.example.demo.service.AService com.example.demo.service.CService.aService)
└─────┘

解决方案

对其中一个进行改造,例如对CService改造,采用如下注入方式:

@Service
public class CService {

    private AService aService; // 去掉@Autowired
    
	// 采用构造器方式,加入Lazy注解
    public CService(@Lazy AService aService) { 
        this.aService = aService;
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5709466.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存