AnnotationConfigApplicationContext作为注解型IOC的入口
ClassPathXmlApplicationContext 作为XML IOC的入口
public AnnotationConfigApplicationContext(Class>... componentClasses) {
this();
register(componentClasses);
refresh();
}
传入一个Class对象
首先this()初始化reader和scanner,创建beanFactory,这个this其实是执行了父类GenericApplicationContext中的初始化方法
/**
* Create a new GenericApplicationContext.
* @see #registerBeanDefinition
* @see #refresh
*/
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
他初始化了一个beanFactory,beanFactory会记录一些bean信息。
Register(class)通过AnnotatedBeanDefinitionReader去doRegisterBean()。
这里其实是把主类解析成BeanDefinition同时会解析主类上的注解会把配置类信息放进beanDefinitionMap。
refresh()方法,refresh是放在AbstractApplicationContext类中的抽象方法,主要是对beanFactory进行一系列配置刷新。
refresh方法
- prepareBeanFactory()为 beanFactory 工厂添加一些单例内置组件,进行预处理
预埋三级缓存
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}
- invokeBeanFactoryPostProcessors() 一个后置方法允许我们按需注入暴露了ConfigurableListableBeanFactory 和BeanDefinitionRegistry 。找出来,排序然后重新注入。主要是对实现后置处理器的方法的一个调用。
处理一些实现了后置处理器postProcessor的类,然后调用postProcessor.postProcessBeanDefinitionRegistry(registry)
@Component
public class BeanDefinitionRegistryPostProcessorTest implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
System.out.println("A");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("B");
}
}
初始化的时候允许自由修改registry与beanFactory
- registerBeanPostProcessors() 这一步是向容器中注入实现了 BeanPostProcessor的类。注意是注册而非使用
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
this.beanPostProcessors.add(beanPostProcessor);
}
- initMessageSource() 初始化messageSource,对messageSource bean进行装配,messageSource是国际化文件
- initApplicationEventMulticaster()对BeanFactory中的ApplicationEventMulticaster的事件进行监听,通过实现ApplicationEventMulticaster接口来监听事件。如果没有则采用SimpleApplicationEventMulticaster来监听事件。初始化事件监听器,一种观察者模式。
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
- registerListeners() 找出实现ApplicationListener的类装配进applicationListeners。其实是放到ApplicationEventMulticaster 广播器里。发布事件通知,对应Listener会收到消息进行处理。
- finishBeanFactoryInitialization() ,直接看里面调用的beanFactory.preInstantiateSingletons()
剩下来的这个步骤就是初始化所有剩余的单实例 bean。RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName)获取。下面会根据是不是FactoryBean来选择初始化方式。普通的直接走getBean()就行。transformedBeanName会获得bean的真实名字
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean> factory = (FactoryBean>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction) ((SmartFactoryBean>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
}
通过getBean()走到dogetBean()。但其实里面最终都会走到getObjectForBeanInstance()。
在getObjectForBeanInstance()方法中会先判断bean是不是FactoryBean,如果不是,就直接返回Bean。
- 如果是FactoryBean,且name是以&符号开头,那么表示的是获取FactoryBean的原生对象,也会直接返回。如果name不是以&符号开头,那么表示要获取FactoryBean中getObject()方法返回的对象即Bean.class。
- 接下来会先尝试从缓存中获取,如果缓存中不存在则getObjectFromFactoryBean()然后doGetObjectFromFactoryBean()这样走下去。这是FactoryBean的流程。
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
再说一下dogetBean(),用到三级缓存的地方是getSingleton()方法,
singletonObjects一级缓存:单例对象缓存池,beanName->Bean,其中存储的是完整的Bean
earlySingletonObjects二级缓存早期的单例对象,beanName->ObjectFactory,存储的是实例化后,属性未赋值的单例对象
singletonFactories三级缓存:单例工厂的缓存,beanName->ObjectFactory,添加进去的时候实例未具备属性
一层一层往下找就是了,最后找不到调用singletonFactory.getObject()
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
- 尝试从一级缓存中查找完整的Bean实例,找到则直接返回.
- 如果无法从一级缓存中查找,对一级缓存进行上锁,然后尝试从二级缓存中查找半成品的Bean.找到直接返回.
- 从三级缓存中查找,找到则放入二级缓存,同时为了保证一个对象实例为单例,将该实例从第三级缓存中进行移除
在这里判断的循环依赖,如果一个beanName可以从单力池里拿到实例,而他还在创建说明这个类循环依赖,就还会走到getObjectForBeanInstance()方法拿到对象。Spring对于循环依赖的处理时不是一个一个去找,而是直接看池子里有没有。
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
如果实在拿不到,就要开始创建了。首先会到ParentBeanFactory中进行递归查找。根据名称和type。对合并后的BeanDefinition进行检测,主要是判断是否为abstract,然后会找到所有依赖的Bean名称,如果循环依赖直接抛异常,然后会递归走getBean。
递归完成后走到getSingleton()走createBean()。真正创建单例Bean前会检测是否正在创建,做点预处理,最后都会走到createBean()。
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
进到createBean()。先获取Bean的Class放到BeanDefinition。经过方法重载以及代理对象判断后走到doCreateBean()。
这里会再进一次缓存,如果拿不到BeanWrapper(包装类对象)则调用createBeanInstance()来创建Bean实例,此时获取类的构造方法createBean,即调用autowireConstructor(),最典型的应用就是Autowire打在构造方法上。mbd.getConstructorArgumentValues()可以从BeanDefinition中拿到构造函数信息,通过resolveConstructorArguments()拿到参数。
// Candidate constructors for autowiring?
Constructor>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
这个时候会把BeanDefinition尽早放进SingletonFactory。然后会进行依赖注入,再看下属性注入,走到populateBean()方法会通过BeanDefinition进行属性判断。这里会选择名称进行注入或者根据类型进行注入。这里最后还是走getBean递归
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
通过名称注入,先通过 unsatisfiedNonSimpleProperties() 找到需要填充的所有属性 name。然后递归getbean加载属性
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
registerDependentBean(propertyName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
类型则是先通过 unsatisfiedNonSimpleProperties() 找到需要填充的所有属性 name,根据传入的参数 pvs 中找出已经加载的 bean,并递归实例化,然后再加入到 pvs 中
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}