本章内容基于Spring Boot 2.2.8
一、背景
ApplicationContext是Spring哲学中最强大的一个概念,他聚合了众多能力,如BeanFactory,他是用户能够接触Spring的通道,他的创建是不是应该足够引起重视?
org.springframework.boot.SpringApplication#createApplicationContext()
官方的说明是:
这是一个策略方法用来创建ApplicationContext,在落到最后默认策略之前,他会接受一个显示设置的application context或application context class。
这段解释要结合代码才好理解,他其实就是在对源代码结构做一个解释,看来作者也是实在没什么话说才找了点话说。
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
二、createApplicationContext()的作用
先从使用角度说明这个方法的作用,对初学者来说是一个非常重要的事情,这样才有可能激发读者思考动力。
1、往里面注册了ConfigurationClassPostProcessor,这个是扫描BeanDefinition的处理器,在后面refresh()时用到
2、
三、源码解读
这里我们多数使用的是servlet web环境所以具体的ApplicationContext是确定的,也就是:
org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
名字很长,但是每个词都有深意,AnnotationConfig表示是通过注解扫描注册Bean的(@Service,@Controller等),ServletWebServer表示是传统Servlet方式的WebServer,ApplicationContext表示应用上下文。这样解释了,是否能记住这个名字了。
始自 Spring Boot 1.0.0
官方对这个类的解释是:
ServletWebServerApplicationContext接受有注解的类作为输入,特别的如@Configuration的类,普通的如@Component,以及符合JSR-330 javax.inject.*注解的类(@Resource)。支持一个一个的注册类(在配置位置配置各个类名),同时也支持classpath扫描批量注册(在配置位置配置扫描包路径)。注意:在有多个@Configuration类的情况下,后配置的@Bean定义会覆盖已存在的bean,通过@Configuration可以特意被用来覆盖一个确定存在的bean。
这个解释说出了主要的特点,肯定是无法通过一两句话说清楚的。这里我们只关注构造函数,注意这里实例化了2个类,这两个类都是非常重要的,请大家高度关注。
还是老规矩,直接说明2个类做了什么事情:
public class AnnotationConfigServletWebServerApplicationContext extends ServletWebServerApplicationContext implements AnnotationConfigRegistry {
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
}
四、org.springframework.context.annotation.ClassPathBeanDefinitionScanner#ClassPathBeanDefinitionScanner()
始自Spring 2.5
官方对这个类的解释是:
五、org.springframework.context.annotation.AnnotatedBeanDefinitionReader
始自 Spring 3.0
官方对这个类的解释是:
是一个方便的编程式注册bean的适配器。他是ClassPathBeanDefinitionScanner的另一种选择,对注解应用同样的解决方案,只不过要手动显式注册。
这个类的作用是解析@Configuration注解的Bean,因为他注册的ConfigurationClassPostProcessor处理器
看看源码:
public class AnnotatedBeanDefinitionReader {
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
this(registry, getOrCreateEnvironment(registry));
}
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
}
目标被转移到了:
org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry)
这个方法会注册以下几个bean
org.springframework.context.annotation.ConfigurationClassPostProcessor
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor(jpa环境激活时)
org.springframework.context.event.EventListenerMethodProcessor
org.springframework.context.event.DefaultEventListenerFactory
这里的每一个类都是后面功能的重要推手。所以AnnotatedBeanDefinitionReader这个类本身就是注册了几个处理器,将工作内容交给其他类,且起作用的时机是后续的某个流程,他是一个埋伏笔的家伙。
public abstract class AnnotationConfigUtils {
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}
public static Set<BeanDefinitionHolder> 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<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;
}
}