AnnotationConfigApplicationContext是注释使用的Bean工厂。
里面包含类读取器,可以将类给注册成BeanDefnition,并且实现了registry方法,可以保存各种BeanDefnition,同时还拥有着BeanFactory对象,可以存取bean
这是Spring最常使用的构造方法
public AnnotationConfigApplicationContext(Class>... componentClasses) {this();register(componentClasses);refresh();
}public AnnotationConfigApplicationContext(String... basePackages) {this();scan(basePackages);refresh();
}public AnnotationConfigApplicationContext() {this.reader = new AnnotatedBeanDefinitionReader(this);this.scanner = new ClassPathBeanDefinitionScanner(this);
}
this主要是做两件事,初始化reader和scanner,无论是reader还是scanner本质都是提供beanDefinition,reader是用于可以读取当前class,并将其转化为beanDefinition,Scanner可以读取字符串,将其路径之下所有含@Component注释的类转化为beanDefinition。对于它们而言,environment都是同一个。
新建Reader主要做两件事,创建环境,和创建几个内部后置处理器,以下分别创建了ConfigurationClassPostProcessor,AutowiredAnnotationBeanPostProcessor,EventListenerMethodProcessor,DefaultEventListenerFactory
ConfigurationClassPostProcessor,用于将Definition中所有注解类转化为beanDefinition
AutowiredAnnotationBeanPostProcessor,用于注入bean完成对象注入
public static Set registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);if (beanFactory != null) {if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);}if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());}}Set 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的本质就是把指定类转换成beanDefinition,而scan的实质,就是把指定string路径下所有含Component注解的类转化为beanDifinition。
为了实现Component的注解识别,在Scanner无参实例化的时候,会顺便创建scanner拦截器,并为其注入Component扫描。
protected void registerDefaultFilters() {// 第一行就注入了this.includeFilters.add(new AnnotationTypeFilter(Component.class));ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();try {this.includeFilters.add(new AnnotationTypeFilter(((Class extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));logger.trace("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");}catch (ClassNotFoundException ex) {// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.}try {this.includeFilters.add(new AnnotationTypeFilter(((Class extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));logger.trace("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");}catch (ClassNotFoundException ex) {// JSR-330 API not available - simply skip.}
}
以下是refresh调用全流程,refresh是由父类AbstractApplicationContext完成书写的
public void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// 验证环境有效性prepareRefresh();// 完成beanFactory的序列化id设置(对于AnnotationConfigApplicationContext而言)ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// 完成一些beanPostProcessor的创建及其它初始化prepareBeanFactory(beanFactory);try {// 空方法postProcessBeanFactory(beanFactory);// 调用BeanFactoryPostProcessors,主要任务是调用ConfigurationClassPostProcessorinvokeBeanFactoryPostProcessors(beanFactory);// 把beanPostProcessor转化为BeanDefinitionregisterBeanPostProcessors(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();// 完成所有BeanDefinition转化为bean的过程,取消懒加载,除非是特殊注明的beanfinishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event.finishRefresh();}//各种有关bean的错误,都会造成单例池的destory方法回调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();}}}