springboot循环依赖

springboot循环依赖会报以下错误信息:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'xxxConfiguration': Unsatisfied dependency expressed through field 'xxxService';
   nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'xxxServiceImpl': Bean with name 'xxxServiceImpl' has
   been injected into other beans [xxxServiceImpl] 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 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.

循环依赖是指两个或多个Bean互相依赖的情况,在Spring容器初始化时会出现循环依赖的问题。对于循环依赖,Spring在初始化过程中采用了“提前暴露”的策略,将尚未完全初始化的Bean对象暴露给其他需要依赖的Bean对象,以便后者能够完成初始化。

常见的循环依赖场景:

@Service
public class AImpl implements IAService {
    @Autowired
    private IBService bService;
}
@Service
public class BImpl implements IBService {
    @Autowired
    private IAService aService;
}

解决循环依赖的方法:

一、A类service引用B类service,B类引用A类mapper
@Service
public class AImpl implements IAService {
    @Autowired
    private IBService bService;
}
@Service
public class BImpl implements IBService {
    @Autowired
    private AMapper aMapper;
}
二、A类service引用B类service,B类使用spring工具类获取A类service实现类的bean
@Service
public class AImpl implements IAService {
    @Autowired
    private IBService bService;
}
@Service
public class BImpl implements IBService {
    public void test() {
        AServiceImpl bean = SpringUtil.getBean(AServiceImpl.class);
    }
}
三、使用@Lazy懒加载注解
@Service
public class AImpl implements IAService {
    @Autowired
    private IBService bService;
}
@Service
public class BImpl implements IBService {
    @Lazy
    @Autowired
    private IAService aService;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值