Spring的配置由基于XML,逐渐演变为基于注解,常用的应用程序上下文也由ClassPathXmlApplicationContext转为AnnotationConfigApplicationContext但基本流程都是一样的。
AnnotationConfigApplicationContext代码如下所示
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//这里由于他有父类,故而会先调用父类的构造方法,然后才会调用自己的构造方法
//在自己构造方法中初始一个读取器和扫描器
this();
register(annotatedClasses);
refresh();
}
AnnotationConfigApplicationContext在实例化的时候会先调用父类的构造方法初始化BeanFactory
,这个类包含很多重要的容器比如beanDefinitionMap
等等
public GenericApplicationContext() {
//这个类包含很多重要的容器比如beanDefinitionMap等等
this.beanFactory = new DefaultListableBeanFactory();
}
this()方法
在this()
方法中主要初始化一个读取器和一个扫描器,扫描器的的作用主要提给程序员程序员使用,在spring进行扫描的时候会再实例化一个扫描器。这里最重要是是AnnotatedBeanDefinitionReader
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
/**
* 可以用来扫描宝或者类,继而转换成bd
* 但实际上我们扫描包不是scanner这个对象,是spring自己new的一个ClassPathBeanDefinitionScanner
* 这里的scanner仅仅是为了程序员能够在外部调用AnnotationConfigApplicationContext对象scan方法
*/
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
AnnotatedBeanDefinitionReader
实例化的时候会调用registerAnnotationConfigProcessors
方法,在beanDefinitionMap
放入几个非常重要的的类,这几个类贯整个Spring容器的生命周期
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
......删除部分代码
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}
return beanDefs;
}
register(annotatedClasses)方法
register(annotatedClasses)
最终会调用registerBeanDefinition
向beanDefinitionMap
注册一个配置类,它的beanDefinition是AnnotatedGenericBeanDefinition。
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
@Nullable BeanDefinitionCustomizer[] customizers) {
//创建一个AnnotatedGenericBeanDefinition
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
......................................
//进行beanDefinition注册
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
refresh()方法
refresh()
方法,每个方法的作用请看注释,这里比较重要的是两个方法是invokeBeanFactoryPostProcessors(beanFactory)
和finishBeanFactoryInitialization(beanFactory)
分别进行类扫描和依赖注入以及AOP
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备工作包括设置启动时间,是否激活标志位,初始化属性源(property source)配置
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//如果是基于XML配置,并BeanFactory工厂不是在构造函数初始的时候进行实例化的,而是调用这个方法。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//对BeanFactory功能进行填充
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//目前是个空方法,如果有需要由子类进行扩展
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//在spring环境中去执行已经被注册的 BeanFactoryPostProcessors,类的扫描就是在这里进行的,它的作用是在
//bean初始化之前做一些干预。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册BeanPostProcessors,BeanPostProcessors的作用是
// 在bean初始化的时候进行干预,比如说进行AOP,这里只是注册,并不会执行
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//为上下文初始化Message源,即不同的语言的消息体,国际化处理
initMessageSource();
// Initialize event multicaster for this context.
//初始化应用消息广播器,并放入 applicationEventMulticaster
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//留给子类初始化其他的Bean
onRefresh();
// Check for listener beans and register them.
//在所有注册的bean中查找Listener bean,注册到消息广播器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//这个方法非常重要,依赖注入和AOP就是在这里进行的。
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人。
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();
}
}
}