1. spring替我们创建的bean,它放在哪里了?
通常而言,我们一般会用到两种bean:singleton和prototype。对于singleton的bean,一旦创建过后,spring会把它存到一个map里面。
DefaultSingletonBeanRegistry类
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
而prototype属性的bean,则是每次获取都会去创建。
2. 类中用Autowired注解修饰的属性,是在什么时候注入值的?
下面的图显示了注入属性的调用栈。
3. spring具体是如何解决循环依赖的?(先看简单情形singleton)
@Component
@Lazy
public class ClassA {
@Autowired
private ClassB companion;
}
@Component
@Lazy
public class ClassB {
@Autowired
private ClassA companion;
}
appCtx.getBean("classA"); // 触发创建bean
spring的debug日志如下(主要就是提前暴露):
Creating shared instance of singleton bean ‘classA‘
Creating instance of bean ‘classA‘
Registered injected element on class [com.zhang.bean.ClassA]: AutowiredFieldElement for private com.zhang.bean.ClassB com.zhang.bean.ClassA.companion
Eagerly caching bean ‘classA‘ to allow for resolving potential circular references
Processing injected element of bean ‘classA‘: AutowiredFieldElement for private com.zhang.bean.ClassB com.zhang.bean.ClassA.companion
Creating shared instance of singleton bean ‘classB‘
Creating instance of bean ‘classB‘
Registered injected element on class [com.zhang.bean.ClassB]: AutowiredFieldElement for private com.zhang.bean.ClassA com.zhang.bean.ClassB.companion
Eagerly caching bean ‘classB‘ to allow for resolving potential circular references
Processing injected element of bean ‘classB‘: AutowiredFieldElement for private com.zhang.bean.ClassA com.zhang.bean.ClassB.companion
Returning eagerly cached instance of singleton bean ‘classA‘ that is not fully initialized yet - a consequence of a circular reference
Autowiring by type from bean name ‘classB‘ to bean named ‘classA‘
postProcessBeforeInitialization classB
Finished creating instance of bean ‘classB‘
Autowiring by type from bean name ‘classA‘ to bean named ‘classB‘
postProcessBeforeInitialization classA
Finished creating instance of bean ‘classA‘