前言
在这篇文章里,最后总结处,我说了会讲讲循环依赖中,其中一个类添加@Async有可能会导致注入失败而抛异常的情况,今天就分析一下。
一、异常表现,抛出内容
1.1 循环依赖的两个class
1. CycleService1
@Service
public class CycleService1 {
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
System.out.println("it's a async move");
}
}
2. CycleService2
@Service
public class CycleService2 {
private CycleService1 cycleService1;
public void init() {
}
@WangAnno
public void alsoDo() {
System.out.println("create cycleService2");
}
}
1.2 启动报错
Bean with name ‘cycleService1’ has been injected into other beans [cycleService2] 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.
解决方案
1. 延迟注入(使用@Lazy注解)
@Service
public class CycleService1 {
@Lazy
@Autowired
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
cycleService2.alsoDo();
System.out.println("it's a async move");
}
}
看过这篇文章的都知道原理了,此处不再累赘
2. 手动延迟注入(使用applicationContext.getBean)
@Service
public class CycleService1 {
@Autowired
private ApplicationContext applicationContext;
private CycleService2 cycleService2;
@WangAnno
@Async
public void doThings() {
if (Objects.isNull(cycleService2)) {
cycleService2 = applicationContext.getBean(CycleService2.class);
}
cycleService2.alsoDo();
System.out.println("it's a async move");
}
}
其实效果是上面加了@Lazy效果是一样的,不过是我们自己在方法执行的过程中手动进行延迟注入而已。
————————————————
版权声明:本文为CSDN博主「liangsheng_g」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/liangsheng_g/article/details/119976614