1. 什么是循环依赖?
循环依赖说白了就是在我们的程序中,类A需要依赖于类B,类B又需要依赖于类A,这时候两个类实例就构成了相互依赖,你中有我,我中有你。
@Component
public class A {
@Autowired
private B b;
}
@Component
public class B {
@Autowired
private A a;
}
2. Spring什么情况下可以帮助我们解决循环依赖?
我们知道在spring中,如果我们的bean是单例的,并且不是通过构造方法进行依赖注入,spring大部分情况下是可以帮助我么解决循环依赖问题的,当然也有
可能解决不了。
(具体参考:这个Spring循环依赖的坑,90%以上的人都不知道)。
3. Prototype类型为什么解决不了循环依赖?
在spring的AbstractBeanFactory中的doGetBean方法中有一个判断,如果是Prototype类型并且该实例正在创建中,直接抛出异常。
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread).
* @param beanName the name of the bean
*/
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
4. 构造方法注入为什么解决不了循环依赖?
思考一个逻辑,spring创建A的时候,发现A的构造函数中需要注入B,然后spring去创建B,这时候发现,B的构造函数中又需要注入A,可是这时候A还在等待B创
建成功后进行注入,A还没创建好呢,这时候就构成了死等待,A等待B创建,B等待A创建,最终的结果就是都进行不下去了,spring检测到后就直接给我们抛异常
了。
5. 自定义BeanPostProcessor
这时候如果我们想要自定义BeanPostProcessor,并且可能需要通过代理原始类,扩展我们的功能,那么这时候,如果我们像下面这样写:
@Component
public class TestBeanPostProcessor implements BeanPostProcessor,MethodInterceptor{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof A){