本周我的项目中遇到了如下报错
报错说的很明确,buildingService 中用到了 divisionalService,divisionalservice 中也用到了 buildingService。在执行构造函数时就呈现了问题。
@Autowired
public BuildingServiceImpl(BuildingRepository buildingRepository,
DivisionalWorkService divisionalWorkService
) {
this.buildingRepository = buildingRepository;
this.divisionalWorkService = divisionalWorkService;
}
咱们想要结构 BuildingService
就须要先结构一个 divisionalWorkService
,然而想要结构divisionalWorkService
又得结构一个 BuildingService
。
很显然后果就是会卡住,对应的解决办法也很简略,就是先让其中一方在不须要另一方的状况下结构进去其中一个, 再去结构另外一个。
具体做法如下:
@Autowired
public DivisionalWorkServiceImpl(DivisionalWorkRepository divisionalWorkRepository,
@Lazy BuildingService buildingService) {
this.divisionalWorkRepository = divisionalWorkRepository;
this.buildingService = buildingService;
}
在其中一方的的构造函数中增加 @Lazy 注解。
上面是我找到的解释:
A simple way to break the cycle is by telling Spring to initialize one of the beans lazily. So, instead of fully initializing the bean, it will create a proxy to inject it into the other bean. The injected bean will only be fully created when it’s first needed.
咱们能够通知 spring 来懒初始化其中一个 bean,而不是齐全初始化这个 bean,spring 会依据所需 bean 创立一个代理,通过此代理来创立所需 bean。当所需 bean 创立完并且用到另一个 bean 时再去齐全初始化另一个 bean,此时有一方已被齐全创立好能够间接创立。
大抵流程: