本周我的项目中遇到了如下报错
报错说的很明确,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,此时有一方已被齐全创立好能够间接创立。
大抵流程:
发表回复