Spring的启动流程可以归纳为三个步骤:
1、初始化Spring容器,注册内置的BeanPostProcessor的BeanDefinition到容器中
2、将配置类的BeanDefinition注册到容器中
3、调用refresh()方法刷新容器
// 初始化容器
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {// 注册 Spring 内置后置处理器的 BeanDefinition 到容器this();// 注册配置类 BeanDefinition 到容器register(annotatedClasses);// 加载或者刷新容器中的Beanrefresh();
}
一、初始化流程:
1、spring容器的初始化时,通过this()调用了无参构造函数,主要做了以下三个事情:
(1)实例化BeanFactory【DefaultListableBeanFactory】工厂,用于生成Bean对象
(2)实例化BeanDefinitionReader注解配置读取器,用于对特定注解(如@Service、@Repository)的类进行读取转化成 BeanDefinition 对象,(BeanDefinition 是 Spring 中极其重要的一个概念,它存储了 bean 对象的所有特征信息,如是否单例,是否懒加载,factoryBeanName 等)
(3)实例化ClassPathBeanDefinitionScanner路径扫描器,用于对指定的包目录进行扫描查找 bean 对象
(1)的解释 :
1.AnnotationConfigApplicationContext
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
}
public GenericApplicationContext() {this.beanFactory = new DefaultListableBeanFactory();}
public AnnotationConfigApplicationContext() {StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");// 额外会创建StandardEnvironmentthis.reader = new AnnotatedBeanDefinitionReader(this);createAnnotatedBeanDefReader.end();this.scanner = new ClassPathBeanDefinitionScanner(this);}
(2)的解释 :
1.
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;// 用来解析@Conditional注解的this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);// 注册AnnotationConfigUtils.registerAnnotationConfigProcessors(this.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;// 用来解析@Conditional注解的this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);// 注册AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);}
BeanDefinitionRegistry数据类型:
它大概有如下功能:
1.以Map<String, BeanDefinition>的形式注册bean
2.根据beanName 删除和获取 beanDefiniation
3.得到持有的beanDefiniation的数目
4.根据beanName 判断是否包含beanDefiniation
// 它继承自 AliasRegistry
public interface BeanDefinitionRegistry extends AliasRegistry {// 关键 -> 往注册表中注册一个新的 BeanDefinition 实例 void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException;// 移除注册表中已注册的 BeanDefinition 实例void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;// 从注册中心取得指定的 BeanDefinition 实例BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;// 判断 BeanDefinition 实例是否在注册表中(是否注册)boolean containsBeanDefinition(String beanName);// 取得注册表中所有 BeanDefinition 实例的 beanName(标识)String[] getBeanDefinitionNames();// 返回注册表中 BeanDefinition 实例的数量int getBeanDefinitionCount();// beanName(标识)是否被占用boolean isBeanNameInUse(String beanName);
}
可以看出,它的默认实现类,主要有三个:SimpleBeanDefinitionRegistry、DefaultListableBeanFactory、GenericApplicationContext
DefaultListableBeanFactory
该类是 BeanDefinitionRegistry 接口的基本实现类,但同时也实现其他了接口的功能,这里只探究下其关于注册 BeanDefinition 实例的相关方法。
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");if (registry instanceof EnvironmentCapable) {return ((EnvironmentCapable) registry).getEnvironment();}return new StandardEnvironment();}
registerAnnotationConfigProcessors;
根据上图分析,代码运行到这里时候,Spring 容器已经构造完毕,那么就可以为容器添加一些内置组件了,其中最主要的组件便是 ConfigurationClassPostProcessor 和 AutowiredAnnotationBeanPostProcessor ,前者是一个 beanFactory 后置处理器,用来完成 bean 的扫描与注入工作,后者是一个 bean 后置处理器,用来完成 @AutoWired 自动注入。
它内部注册了AnnotationConfigProcessors的BeanDefinition,包括:
ConfigurationClassPostProcessor
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
EventListenerMethodProcessor
DefaultEventListenerFactory
这些Processors注册好后,AnnotationConfigApplicationContext调用register来注册用户的配置类,将注册为AnnotatedGenericBeanDefinition,后面ConfigurationClassPostProcessor会在正式初始化用户Bean之前,处理@Configuration配置类下面的@Bean注解的方法。
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);if (beanFactory != null) {// 设置beanFactory的OrderComparator为AnnotationAwareOrderComparator// 它是一个Comparator,是一个比较器,可以用来进行排序,比如new ArrayList<>().sort(Comparator);if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);}// 用来判断某个Bean能不能用来进行依赖注入if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());}}Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);// 注册ConfigurationClassPostProcessor类型的BeanDefinitionif (!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));}// 注册AutowiredAnnotationBeanPostProcessor类型的BeanDefinition 用于依赖注入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));}// 注册CommonAnnotationBeanPostProcessor类型的BeanDefinition // 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));}// 注册PersistenceAnnotationBeanPostProcessor类型的BeanDefinition// 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));}// 注册EventListenerMethodProcessor类型的BeanDefinition,用来处理@EventListener注解的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));}// 注册DefaultEventListenerFactory类型的BeanDefinition,用来处理@EventListener注解的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;}
(3)
这个就是来扫描我们注解,比如@Component,@Repository,@Service,@Controller
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {this(registry, true);}
@Overridepublic void register(Class<?>... componentClasses) {Assert.notEmpty(componentClasses, "At least one component class must be specified");StartupStep registerComponentClass = this.getApplicationStartup().start("spring.context.component-classes.register").tag("classes", () -> Arrays.toString(componentClasses));this.reader.register(componentClasses);registerComponentClass.end();}
public void register(Class<?>... componentClasses) {for (Class<?> componentClass : componentClasses) {registerBean(componentClass);}}
public void registerBean(Class<?> beanClass) {doRegisterBean(beanClass, null, null, null, null);}
这个步骤主要是用来解析用户传入的 Spring 配置类,解析成一个 BeanDefinition 然后注册到容器中,主要源码如下:
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {// 解析传入的配置类,实际上这个方法既可以解析配置类,也可以解析 Spring bean 对象AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);// 判断是否需要跳过,判断依据是此类上有没有 @Conditional 注解if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {return;}abd.setInstanceSupplier(instanceSupplier);ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);abd.setScope(scopeMetadata.getScopeName());String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));// 处理类上的通用注解AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);if (qualifiers != null) {for (Class<? extends Annotation> qualifier : qualifiers) {if (Primary.class == qualifier) {abd.setPrimary(true);}else if (Lazy.class == qualifier) {abd.setLazyInit(true);}else {abd.addQualifier(new AutowireCandidateQualifier(qualifier));}}}// 封装成一个 BeanDefinitionHolderfor (BeanDefinitionCustomizer customizer : definitionCustomizers) {customizer.customize(abd);}BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);// 处理 scopedProxyModedefinitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);// 把 BeanDefinitionHolder 注册到 registryBeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}