@Transactional和@Async的循环依赖问题
在一个类A方法上同时添加了@Transactional和@Async两个注解后,
@Service("transationServiceImpl")
public class TransationServiceImpl implements TransationService{
@Autowired
TransationService transationService;
@Transactional
@Async
@Override
public void A(){
}
}
理论上单例的循环依赖是允许的。但是我们启动容器会报错,从报错的字面意思来看,是存在了多版本的循环依赖
org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name ‘transationServiceImpl’: Bean with name ‘transationServiceImpl’ has been injected into other beans [transationServiceImpl] 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.
- 第一次创建TransationServiceImpl实例的时候会从缓存中获取实例 ,如果缓存里面有实例则直接返回,第一次创建的时候缓存中是没有实例的
- 缓存中没有则创建TransationServiceImpl的实例,最终会走到doCreateBean方法中进行实例化
- 实例化业务类后依赖注入会触发第二次业务类的getBean操作之前,三级缓存会建立业务类和ObjectFactory的映射关系
- 第二次进来的时候,由于第一次实例化的时候在三级缓存中建立了映射关系,所以第二次会从缓存中获取实例
- 三级缓存的getObject方法会调用到getEarlyBeanReference中,是获取事务代理的BeanPostProcessor类型是SmartInstantiationAwareBeanPostProcessor类型的,所以事务代理的BeanPostProcessor会进来,然后生成代理,而@Async异步代理的BeanPostProcessor,但是不是SmartInstantiationAwareBeanPostProcessor类型的
- 异步代理时会生成异步的代理对象,一个是事务的代理对象,两个对象不一致导致。