目前已经是springboot的时代,spring的加载已经完全注解化,配置类和xml的对比是最大的优点在于解耦,不需要在xml配置上依赖关心,只需注解即可实现依赖,也都交给了spring处理,省心。
使用配置类的放上启动加载spring:
public static void main(String[] args) {
ApplicationContext context=new AnnotationConfigApplicationContext(xxx.class);
}
初始的时候,这个类里面所有的内容都是空的,或者是默认值:
构造函数里面执行了三句:
this();调用了本类的无参构造方法,触发了父类的无参构造方法。
3-1首先,父类创建了beanFactory
查看this变量:这时候可以看到beanFactory已经被创建
3-2创建了reader和scanner
执行第一句,查看可以看到reader已经被创建:
打开this下的beanFactory,可以看到里面多出5个基础的类,被称为创世纪的类(后置处理器):
这是怎么加载的呢,看代码:
中创建reader的时候,在构造函数中,同时注册了配置的处理器,也就是创世纪的类:
进入到对应的方法中可以看到创建的过程。
scanner 的创建没有其他影响。再看下一步的执行
执行完注册方法,将配置类的bean定义注册进来了,查看变化:
public void register(Class<?>... componentClasses) {
for (Class<?> componentClass : componentClasses) {
registerBean(componentClass);
}
}
读取器,reader读取类,将其注册:
本次是把传递的类注册进来。
refresh();
最重要的方法,在这里注册所有的bean,并实例化bean
进入该方法:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
prepareRefresh();
有时间再继续写吧。