Springboot循环依赖

1. 问题

SpringBoot项目启动时出错,主要日志如下:

org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'chanService': Bean with name 'chanService' has been injected into other beans [publishService] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
2. 报错原因

模块间循环注入,即ClassA中引用ClassB、ClassB中引用ClassA。导致Spring在初始化bean的时候不知道先初始化哪个而报错。

3. 解决方案有2个

方案一 代码重构
方案二 使用注解@Lazy,即

public class ClassA {
	@Autowired
	@Lazy
	ClassB classB;
}

public class ClassB {
	@Autowired
	@Lazy
	ClassA classA;
}

你可能感兴趣的:(Springboot学习,Springboot,循环注入)