spring利用三级缓存解决循环依赖
@Service
class AService{
@Autowired
BService bservice
}
@Service
class BService{
@Autowired
AService aservice
}
但是根据spring bean的生命周期
@Autowired先于BeanPostProcessor
这样如果先初始化AService,缓存了A的earlyBean
当要注入BService对BService进行初始化时
BService注入的是A的earlyBean
BService初始化完,然后AService执行完所有依赖注入后
A执行BeanPostProcessor的方法
对A进行代理包装
这个时候A最终的bean不是B中注入的bean
这不是有问题吗?
另外有说@Lazy可以解决这个问题
但是@Lazy只是让被注解的类在getBean()时加载
感觉上面例子中,B注不注解Lazy,都是由getBean()时加载
感觉加不加一样的啊
我哪里理解错了吗?
还有@Lazy如果和 @Autowired一起用,如下,google了一下,好像是说如果改被注入的bean被使用时才初始化,我试了一下,好像不是的啊
@Service
class AService{
@Lazy
@Autowired
BService bservice
}
--