赞
踩
Spring启动就是在初始化相关对象(BeanFactory)与调用refresh()方法
这里以 AnnotationConfigApplicationContext 为例
初始化:
- public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
- // 通过父级 构造 DefaultListableBeanFactory
- // 通过 new 创建AnnotatedBeanDefinitionReader和ClassPathBeanDefinitionScanner对象
- this();
- // 注册配置类 BeanDefinition 容器中
- register(componentClasses);
- // 加载或刷新容器中的Bean
- refresh();
- }
流程总结:
执行this方法:
- public AnnotationConfigApplicationContext() {
- // 一种计时的东西
- StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");
- this.reader = new AnnotatedBeanDefinitionReader(this);
- createAnnotatedBeanDefReader.end();
- this.scanner = new ClassPathBeanDefinitionScanner(this);
- }
-
- // 父类初始化加载 DefaultListableBeanFactory
- public GenericApplicationContext() {
- this.beanFactory = new DefaultListableBeanFactory();
- }
流程总结:
构建AnnotatedBeanDefinitionReader对象
- 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 static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
- BeanDefinitionRegistry registry, @Nullable Object source) {
-
- // 进行类型的转换,将BeanDefinitionRegistry转换成 DefaultListableBeanFactory
- DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
- if (beanFactory != null) {
- // 构建一个 AnnotationAwareOrderComparator 比较器 用来后面对Order和Priority进行排序
- 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添加到BeanDefinition中
- 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));
- }
- // 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中 @Resource、@PostConstruct @PreDestory注解
- if (jakartaAnnotationsPresent && !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));
- }
- // jsr250Present 添加一个internalJsr250AnnotationProcessor后置处理器
- if (jsr250Present && !registry.containsBeanDefinition(JSR250_ANNOTATION_PROCESSOR_BEAN_NAME)) {
- try {
- RootBeanDefinition def = new RootBeanDefinition(InitDestroyAnnotationBeanPostProcessor.class);
- def.getPropertyValues().add("initAnnotationType", classLoader.loadClass("javax.annotation.PostConstruct"));
- def.getPropertyValues().add("destroyAnnotationType", classLoader.loadClass("javax.annotation.PreDestroy"));
- def.setSource(source);
- beanDefs.add(registerPostProcessor(registry, def, JSR250_ANNOTATION_PROCESSOR_BEAN_NAME));
- }
- catch (ClassNotFoundException ex) {
- }
- }
-
- // 如果你的系统中启用了JPA的方式,那么这里添加一个JPA的后置处理器
- 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;
- }
流程总结:
构建ClassPathBeanDefinitionScanner对象
- public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
- Environment environment, @Nullable ResourceLoader resourceLoader) {
-
- Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
- this.registry = registry;
-
- // 这里会根据 useDefaultFilters 选择是否注册对应的 TypeFilter
- if (useDefaultFilters) {
- // 注册@Component对应的AnnotationTypeFilter
- // 扫描的时候扫这个注解
- registerDefaultFilters();
- }
- // 设置环境
- setEnvironment(environment);
- // 设置资源加载路径 (扫描路径)
- setResourceLoader(resourceLoader);
- }
流程总结:
执行regist方法:
- public void register(Class<?>... componentClasses) {
- for (Class<?> componentClass : componentClasses) {
- /**
- 将配置类注册到BeanDefinition当中
- */
- registerBean(componentClass);
- }
- }
-
-
- private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
- @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
- @Nullable BeanDefinitionCustomizer[] customizers) {
-
- AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
- //@Conditional装配条件判断是否需要跳过注册
- if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
- return;
- }
-
- // 设置回调
- abd.setInstanceSupplier(supplier);
- // 解析@Scope注解的结果为ScopeMetadata
- ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
- abd.setScope(scopeMetadata.getScopeName());
- // 生成配置类的BeanName
- String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
-
- // 通用注解解析到abd结构中,主要是处理Lazy, primary DependsOn, Role ,Description这五个注解
- 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));
- }
- }
- }
- if (customizers != null) {
- for (BeanDefinitionCustomizer customizer : customizers) {
- customizer.customize(abd);
- }
- }
-
- BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
- definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
- BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
- }
流程总结:
总结:
初始化到这里位置,总共存在6个类存在于BeanDefinitionMap当中
refresh()方法
- public void refresh() throws BeansException, IllegalStateException {
- synchronized (this.startupShutdownMonitor) {
- StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
-
- // Prepare this context for refreshing.
- //容器启动前准备工作,也就是设置容器当前的状态和记录启动开始时间以及初始化资源数据以及验证下我们需要验证的一些资源key是否存在
- prepareRefresh();
-
- // Tell the subclass to refresh the internal bean factory.
-
- ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
-
- // Prepare the bean factory for use in this context.
- // 准备BeanFactory
- // 1. 设置BeanFactory的类加载器、SpringEL表达式解析器、类型转化注册器
- // 2. 添加三个BeanPostProcessor,注意是具体的BeanPostProcessor实例对象
- // 3. 记录ignoreDependencyInterface
- // 4. 记录ResolvableDependency
- // 5. 添加三个单例Bean
- // 6. 将系统的环境信息、spring容器的启动环境信息、操作系统的环境信息直接注册成一个单例的bean
- // 7. 去除一些在byType或者byName的时候需要过滤掉的一些bean(spring在依赖注入的时候会先在这些默认注册的bean中进行byType找
- // 如果找到了,就加入到列表中,简单来说就是比如你在bean中依赖注入了ApplicationContext context,那么spring会把默认注册的这些bean 中找到然后进行注册)
- prepareBeanFactory(beanFactory);
-
- try {
- // Allows post-processing of the bean factory in context subclasses.
- // 版本方法,留给子类使用
- postProcessBeanFactory(beanFactory);
-
- StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
- // Invoke factory processors registered as beans in the context.
- // BeanFactory准备好了之后,执行BeanFactoryPostProcessor,开始对BeanFactory进行处理
- // 这里就是调用后置处理器,程序执行到这里为止,还没有添加的有我们用户自定义的后置处理器
- // 这里会执行ConfigurationClassPostProcessor进行@Component的扫描,扫描得到BeanDefinition,并注册到beanFactory中
- // 处理@Import注解
- // 如果我们的配置类是@Configuration的,那么会生成这个配置类的CGLIB代理类,如果没有加@Configuration,则就是一个普通Bean
- // 注意:扫描的过程中可能又会扫描出其他的BeanFactoryPostProcessor,那么这些BeanFactoryPostProcessor也得在这一步执行
- invokeBeanFactoryPostProcessors(beanFactory);
-
- // Register bean processors that intercept bean creation.
- // 将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去
- registerBeanPostProcessors(beanFactory);
- beanPostProcess.end();
-
- // Initialize message source for this context.
- // 初始化国际化资源
- // 设置ApplicationContext的MessageSource,要么是用户设置的,要么是DelegatingMessageSource
- initMessageSource();
-
- // Initialize event multicaster for this context.
- // 事件注册器初始化
- // 设置ApplicationContext的applicationEventMulticaster,要么是用户设置的,要么是SimpleApplicationEventMulticaster
- initApplicationEventMulticaster();
-
- // Initialize other special beans in specific context subclasses.
- // 版本方法留个子类使用
- onRefresh();
-
- // Check for listener beans and register them.
- // 将容器中和BeanDefinitionMap中的监听器添加到事件监听器中
- // 把定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件
- registerListeners();
-
- // Instantiate all remaining (non-lazy-init) singletons.
- // 创建单例池,创建非懒加载的单例bean放入到单例池当中
- 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();
- contextRefresh.end();
- }
- }
- }
流程总结:
prepareRefresh() 方法
- protected void prepareRefresh() {
- // Switch to active.
- //记录启动时间
- this.startupDate = System.currentTimeMillis();
- // 设置当前容器为激活状态
- this.closed.set(false);
- this.active.set(true);
-
- if (logger.isDebugEnabled()) {
- if (logger.isTraceEnabled()) {
- logger.trace("Refreshing " + this);
- }
- else {
- logger.debug("Refreshing " + getDisplayName());
- }
- }
-
- // Initialize any placeholder property sources in the context environment.
- // 初始化property资源文件 Spring没有实现 比如子类可以把ServletContext中的参数对设置到Environment
- initPropertySources();
-
- // Validate that all properties marked as required are resolvable:
- // see ConfigurablePropertyResolver#setRequiredProperties
- // 验证现有的系统资源必须存在哪些资源的key
- getEnvironment().validateRequiredProperties();
-
- // Store pre-refresh ApplicationListeners...
- // 初始化监听器,如果这个监听器不为空,然后清空监听器
- if (this.earlyApplicationListeners == null) {
- this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
- }
- else {
- // Reset local application listeners to pre-refresh state.
- this.applicationListeners.clear();
- this.applicationListeners.addAll(this.earlyApplicationListeners);
- }
-
- // Allow for the collection of early ApplicationEvents,
- // to be published once the multicaster is available...
- this.earlyApplicationEvents = new LinkedHashSet<>();
- }
流程总结:
- // AbstractRefreshableWebApplicationContext类
- protected void initPropertySources() {
- ConfigurableEnvironment env = getEnvironment();
- if (env instanceof ConfigurableWebEnvironment) {
- ((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
- }
- }
obtainFreshBeanFactory() 方法
- protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
- // 模版方法刷新BeanFactory
- refreshBeanFactory();
- return getBeanFactory();
- }
流程总结:
- protected final void refreshBeanFactory() throws BeansException {
- // 是否存在BeanFactory
- if (hasBeanFactory()) {
- // 销毁bean,关闭BeanFactory,同时会去执行Bean的销毁逻辑
- destroyBeans();
- closeBeanFactory();
- }
- try {
- // 创建BeanFactory,然后去加载BeanDefinition
- DefaultListableBeanFactory beanFactory = createBeanFactory();
- beanFactory.setSerializationId(getId());
- customizeBeanFactory(beanFactory);
- loadBeanDefinitions(beanFactory);
- this.beanFactory = beanFactory;
- }
- catch (IOException ex) {
- throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
- }
- }
注: AnnotationConfigApplicationContext在初始化父类去创建BeanFactory,而AnnotationConfigWebApplicationContext是在该方法执行的时候判断然后去生成BeanFactory。
prepareBeanFactory(beanFactory);方法
- protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
- // Tell the internal bean factory to use the context's class loader etc.
- // 设置类加载器,如果自己设置拿设置的,没有拿默认的
- // 由于Spring是通过ASM技术拿到class的全限定名,后面得用类加载器去生成Bean
- beanFactory.setBeanClassLoader(getClassLoader());
-
- // Spring5.3中新增的功能,可以选择是否开启Spel功能,shouldIgnoreSpel默认为false,表示开启
- if (!shouldIgnoreSpel) {
- beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
- }
-
- // 添加一个ResourceEditorRegistrar,注册一些级别的类型转化器
- // String转file,Integer等
- beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
-
- // Configure the bean factory with context callbacks.
- // 组成一个BeanPostProcessor,用来处理EnvironmentAware、EmbeddedValueResolverAware等回调
- // 那么它会在bean的实例化前来调用这些aware的回调方法
- beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
-
- // 如果一个属性对应的set方法在ignoredDependencyInterfaces接口中被定义了,则该属性不会进行自动注入
- //(是Spring中的自动注入,不是@Autowired)
- // Spring 依赖注入会扫描所有set方法,但是会排除以下几个ignoreDependencyInterface
- beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
- beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
- beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
- beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
- beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
- beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
- beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
-
- // BeanFactory interface not registered as resolvable type in a plain factory.
- // MessageSource registered (and found for autowiring) as a bean.
- // Spring 将这四个类放到一个map(resolvableDependencies)当中,当我们依赖注入的时候findAutowireCandidates
- // spring容器会给你直接从resolvableDependencies中找到然后直接给你注入
- beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
- beanFactory.registerResolvableDependency(ResourceLoader.class, this);
- beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
- beanFactory.registerResolvableDependency(ApplicationContext.class, this);
-
- // Register early post-processor for detecting inner beans as ApplicationListeners.
- // ApplicationListenerDetector负责把ApplicantsListener类型的Bean注册到ApplicationContext中
- beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
-
- // Detect a LoadTimeWeaver and prepare for weaving, if found.
- // Aspectj本身是通过编译期进行代理的,在Spring中就跟LoadTimeWeaver有关
- if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
- beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
- // Set a temporary ClassLoader for type matching.
- beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
- }
-
- // Register default environment beans.
- // 将environment直接注册成一个单例bean,environment是系统的环境变量信息
- if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
- beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
- }
- // 将系统中的属性配置信息注册一个bean,bean的名字就是systemProperties
- if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
- beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
- }
- // 将系统的环境变量注册成一个单例bean,systemEnvironment
- if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
- beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
- }
- // 将监控对象注册成一个单例Bean
- if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
- beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
- }
- }
流程总结:
invokeBeanFactoryPostProcessors(beanFactory);方法
- public static void invokeBeanFactoryPostProcessors(
- ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
-
- // Invoke BeanDefinitionRegistryPostProcessors first, if any.
- Set<String> processedBeans = new HashSet<>();
-
- if (beanFactory instanceof BeanDefinitionRegistry) {
- BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
- List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
- List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
-
- // beanFactoryPostProcessors集合一般情况下都是空的,除非我们手动调用容器的addBeanFactoryPostProcessor方法添加了
- // beanFactoryPostProcessors中可能包含了:普通BeanFactoryPostProcessor对象和BeanDefinitionRegistryPostProcessor对象
- // 对于BeanDefinitionRegistryPostProcessor对象,会执行自己的postProcessBeanDefinitionRegistry()方法
- for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
- if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
- BeanDefinitionRegistryPostProcessor registryProcessor =
- (BeanDefinitionRegistryPostProcessor) postProcessor;
- registryProcessor.postProcessBeanDefinitionRegistry(registry);
- registryProcessors.add(registryProcessor);
- }
- else {
- regularPostProcessors.add(postProcessor);
- }
- }
-
- // Do not initialize FactoryBeans here: We need to leave all regular beans
- // uninitialized to let the bean factory post-processors apply to them!
- // Separate between BeanDefinitionRegistryPostProcessors that implement
- // PriorityOrdered, Ordered, and the rest.
- List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
-
- // 执行扫描出来的BeanDefinitionRegistryPostProcessor
-
- // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
- String[] postProcessorNames =
- beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- }
- }
- // 升序排序
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
- currentRegistryProcessors.clear();
-
- // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
- postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- // processedBeans表示该beanFactoryPostProcessor的postProcessBeanDefinitionRegistry()方法已经执行过了,不再重复执行
- if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
- currentRegistryProcessors.clear();
-
- // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
- // 执行哪些没有实现了PriorityOrdered或Ordered接口的普通BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
- // 在这个过程中可能会向BeanFactory中注册另外的BeanDefinitionRegistryPostProcessor,所以需要while,直到确定所有的BeanDefinitionRegistryPostProcessor都执行完了
- // 在这个过程中注册的BeanDefinitionRegistryPostProcessor,所实现的PriorityOrdered或Ordered接口可能会不按顺序执行
- // 比如 A注册了B和C,B又注册了D和E,那么B和C会按顺序执行,D和E也会按顺序执行,但是B、C、D、E整体不能保证是顺序执行
- boolean reiterate = true;
- while (reiterate) {
- reiterate = false;
- postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
- for (String ppName : postProcessorNames) {
- if (!processedBeans.contains(ppName)) {
- currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
- processedBeans.add(ppName);
- reiterate = true;
- }
- }
- sortPostProcessors(currentRegistryProcessors, beanFactory);
- registryProcessors.addAll(currentRegistryProcessors);
- invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
- currentRegistryProcessors.clear();
- }
-
- // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
- // 执行完BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法后,
- // 再执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法
- invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
-
- // 执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法
- invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
- }
-
- else {
- // Invoke factory processors registered with the context instance.
- invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
- }
-
- // 执行扫描出来的普通BeanFactoryPostProcessor
-
- // Do not initialize FactoryBeans here: We need to leave all regular beans
- // uninitialized to let the bean factory post-processors apply to them!
- String[] postProcessorNames =
- beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
-
- // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
- // Ordered, and the rest.
- List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
- List<String> orderedPostProcessorNames = new ArrayList<>();
- List<String> nonOrderedPostProcessorNames = new ArrayList<>();
- // 先进行分类
- for (String ppName : postProcessorNames) {
- if (processedBeans.contains(ppName)) {
- // skip - already processed in first phase above
- }
- else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
- }
- else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
- orderedPostProcessorNames.add(ppName);
- }
- else {
- nonOrderedPostProcessorNames.add(ppName);
- }
- }
-
- // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
- sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
-
- // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
- List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
- for (String postProcessorName : orderedPostProcessorNames) {
- orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
- }
- sortPostProcessors(orderedPostProcessors, beanFactory);
- invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
-
- // Finally, invoke all other BeanFactoryPostProcessors.
- List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
- for (String postProcessorName : nonOrderedPostProcessorNames) {
- nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
- }
- invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
-
- // Clear cached merged bean definitions since the post-processors might have
- // modified the original metadata, e.g. replacing placeholders in values...
- beanFactory.clearMetadataCache();
- }
流程总结:
registerBeanPostProcessors(beanFactory);方法
- public static void registerBeanPostProcessors(
- ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
-
- // 拿到所有的BeanPostProcessor
- String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
-
- // Register BeanPostProcessorChecker that logs an info message when
- // a bean is created during BeanPostProcessor instantiation, i.e. when
- // a bean is not eligible for getting processed by all BeanPostProcessors.
- // beanProcessorTargetCount表示BeanFactory中所有的BeanPostProcessor数量,+1表示BeanPostProcessorChecker
- int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
- beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
-
- // Separate between BeanPostProcessors that implement PriorityOrdered,
- // Ordered, and the rest.
- List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
- List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
- List<String> orderedPostProcessorNames = new ArrayList<>();
- List<String> nonOrderedPostProcessorNames = new ArrayList<>();
- for (String ppName : postProcessorNames) {
- if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
- BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
- priorityOrderedPostProcessors.add(pp);
- if (pp instanceof MergedBeanDefinitionPostProcessor) {
- internalPostProcessors.add(pp);
- }
- }
- else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
- orderedPostProcessorNames.add(ppName);
- }
- else {
- nonOrderedPostProcessorNames.add(ppName);
- }
- }
-
- // First, register the BeanPostProcessors that implement PriorityOrdered.
- // 升序排序
- sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
- registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
-
- // Next, register the BeanPostProcessors that implement Ordered.
- List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
- for (String ppName : orderedPostProcessorNames) {
- BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
- orderedPostProcessors.add(pp);
- if (pp instanceof MergedBeanDefinitionPostProcessor) {
- internalPostProcessors.add(pp);
- }
- }
- sortPostProcessors(orderedPostProcessors, beanFactory);
- registerBeanPostProcessors(beanFactory, orderedPostProcessors);
-
- // Now, register all regular BeanPostProcessors.
- List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
- for (String ppName : nonOrderedPostProcessorNames) {
- BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
- nonOrderedPostProcessors.add(pp);
- if (pp instanceof MergedBeanDefinitionPostProcessor) {
- internalPostProcessors.add(pp);
- }
- }
- registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
-
- // Finally, re-register all internal BeanPostProcessors.
- // MergedBeanDefinitionPostProcessor排在最后
- sortPostProcessors(internalPostProcessors, beanFactory);
- registerBeanPostProcessors(beanFactory, internalPostProcessors);
-
- // Re-register post-processor for detecting inner beans as ApplicationListeners,
- // moving it to the end of the processor chain (for picking up proxies etc).
- // ApplicationListenerDetector放在所有BeanPostProcessor之后,注意ApplicationListenerDetector的equals()方法实现
- beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
- }
流程总结:
initMessageSource();方法
- protected void initMessageSource() {
- ConfigurableListableBeanFactory beanFactory = getBeanFactory();
- if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
- // 这里是初始化国际化资源信息,在单例池中看是否有一个bean是messageSource,如果有
- this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
- // Make MessageSource aware of parent MessageSource.
- if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
- HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
- if (hms.getParentMessageSource() == null) {
- // Only set parent context as parent MessageSource if no parent MessageSource
- // registered already.
- // 拿父ApplicationContext的messageSource作为this.messageSource的父messageSource
- hms.setParentMessageSource(getInternalParentMessageSource());
- }
- }
- if (logger.isTraceEnabled()) {
- logger.trace("Using MessageSource [" + this.messageSource + "]");
- }
- }
- else {
- // Use empty MessageSource to be able to accept getMessage calls.
- DelegatingMessageSource dms = new DelegatingMessageSource();
- dms.setParentMessageSource(getInternalParentMessageSource());
- this.messageSource = dms;
- beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
- if (logger.isTraceEnabled()) {
- logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
- }
- }
- }
总结流程:
自定义MessageSource
-
- public MessageSource messageSource() {
- ResourceBundleMessageSource message = new ResourceBundleMessageSource();
- message.setBasename("message");
- return messageSource;
- }
initApplicationEventMulticaster();方法
- protected void initApplicationEventMulticaster() {
- ConfigurableListableBeanFactory beanFactory = getBeanFactory();
- // 判断是否定义了applicationEventMulticaster事件广播器,如果存在直接赋值。
- if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
- this.applicationEventMulticaster =
- beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
- if (logger.isTraceEnabled()) {
- logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
- }
- }
- // 如果不存在就默认创建一个SimpleApplicationEventMulticaster 事件广播器
- else {
- this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
- beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
- if (logger.isTraceEnabled()) {
- logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
- "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
- }
- }
- }
流程总结:创建事件广播器,初始化事件的发布器。
registerListeners();方法
- protected void registerListeners() {
- // Register statically specified listeners first.
- // 将所有的监听器添加到事件发布器当中。
- for (ApplicationListener<?> listener : getApplicationListeners()) {
- getApplicationEventMulticaster().addApplicationListener(listener);
- }
-
- // Do not initialize FactoryBeans here: We need to leave all regular beans
- // uninitialized to let post-processors apply to them!
- // 获取FactoryBean调用getObject方法生成的ApplicationListener,将其添加到事件发布器中。
- String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
- for (String listenerBeanName : listenerBeanNames) {
- getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
- }
-
- // Publish early application events now that we finally have a multicaster...
- // 添加了事件监听器后,判断是否有earlyApplicationEvents,如果有就使用事件广播器发布earlyApplicationEvents
- // earlyApplicationEvents表示在事件广播器还没生成好之前ApplicationContext所发布的事件
- Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
- this.earlyApplicationEvents = null;
- if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
- for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
- getApplicationEventMulticaster().multicastEvent(earlyEvent);
- }
- }
- }
事件发布机制的相关类总结:
SimpleApplicationEventMulticaster:默认情况下的事件发布器
ApplicationListenerDetector,EventListenerMethodProcessor,DefaultEventListenerFactory。
如果判断该类为监听类 ApplicationListenerDetector BeanPostProcessor(实现方式)
- // 初始化后的方法,来判断是否为ApplicationListener类型
- public Object postProcessAfterInitialization(Object bean, String beanName) {
- if (bean instanceof ApplicationListener) {
- // potentially not detected as a listener by getBeanNamesForType retrieval
- Boolean flag = this.singletonNames.get(beanName);
- if (Boolean.TRUE.equals(flag)) {
- // singleton bean (top-level or inner): register on the fly
- this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
- }
- else if (Boolean.FALSE.equals(flag)) {
- if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
- // inner bean with other scope - can't reliably process events
- logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
- "but is not reachable for event multicasting by its containing ApplicationContext " +
- "because it does not have singleton scope. Only top-level listener beans are allowed " +
- "to be of non-singleton scope.");
- }
- this.singletonNames.remove(beanName);
- }
- }
- return bean;
- }
判断方法是监听方法:EventListenerMethodProcessor ,DefaultEventListenerFactory(注解)
- public void afterSingletonsInstantiated() {
- ConfigurableListableBeanFactory beanFactory = this.beanFactory;
- Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set");
- String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
- for (String beanName : beanNames) {
- if (!ScopedProxyUtils.isScopedTarget(beanName)) {
-
- // 拿到当前Bean对象的类型
- Class<?> type = null;
- try {
- type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
- }
- catch (Throwable ex) {
- // An unresolvable bean type, probably from a lazy bean - let's ignore it.
- if (logger.isDebugEnabled()) {
- logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
- }
- }
- if (type != null) {
- if (ScopedObject.class.isAssignableFrom(type)) {
- try {
- Class<?> targetClass = AutoProxyUtils.determineTargetClass(
- beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));
- if (targetClass != null) {
- type = targetClass;
- }
- }
- catch (Throwable ex) {
- // An invalid scoped proxy arrangement - let's ignore it.
- if (logger.isDebugEnabled()) {
- logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex);
- }
- }
- }
- try {
- processBean(beanName, type);
- }
- catch (Throwable ex) {
- throw new BeanInitializationException("Failed to process @EventListener " +
- "annotation on bean with name '" + beanName + "'", ex);
- }
- }
- }
- }
- }
-
-
- private void processBean(final String beanName, final Class<?> targetType) {
- if (!this.nonAnnotatedClasses.contains(targetType) &&
- AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
- !isSpringContainerClass(targetType)) {
-
- // 找到所有加了@EventListener注解的方法
- Map<Method, EventListener> annotatedMethods = null;
- try {
- annotatedMethods = MethodIntrospector.selectMethods(targetType,
- (MethodIntrospector.MetadataLookup<EventListener>) method ->
- AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
- }
- catch (Throwable ex) {
- // An unresolvable type in a method signature, probably from a lazy bean - let's ignore it.
- if (logger.isDebugEnabled()) {
- logger.debug("Could not resolve methods for bean with name '" + beanName + "'", ex);
- }
- }
- if (CollectionUtils.isEmpty(annotatedMethods)) {
- this.nonAnnotatedClasses.add(targetType);
- if (logger.isTraceEnabled()) {
- logger.trace("No @EventListener annotations found on bean class: " + targetType.getName());
- }
- }
- else {
- // Non-empty set of methods
- ConfigurableApplicationContext context = this.applicationContext;
- Assert.state(context != null, "No ApplicationContext set");
- List<EventListenerFactory> factories = this.eventListenerFactories;
- Assert.state(factories != null, "EventListenerFactory List not initialized");
- for (Method method : annotatedMethods.keySet()) {
- for (EventListenerFactory factory : factories) {
- // 利用EventListenerFactory来对加了@EventListener注解的方法生成ApplicationListener对象
- if (factory.supportsMethod(method)) {
- Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
- ApplicationListener<?> applicationListener =
- factory.createApplicationListener(beanName, targetType, methodToUse);
- if (applicationListener instanceof ApplicationListenerMethodAdapter) {
- ((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
- }
- context.addApplicationListener(applicationListener);
- break;
- }
- }
- }
- if (logger.isDebugEnabled()) {
- logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" +
- beanName + "': " + annotatedMethods);
- }
- }
- }
- }
流程总结:
finishBeanFactoryInitialization(beanFactory);方法
- protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
- // Initialize conversion service for this context.
- // 如果BeanFactory中存在名字叫conversionService的Bean,则设置到BeanFactory中
- // ConversionService是用来进行类型转换的
- if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
- beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
- beanFactory.setConversionService(
- beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
- }
-
- // Register a default embedded value resolver if no BeanFactoryPostProcessor
- // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
- // at this point, primarily for resolution in annotation attribute values.
- // 设置默认的占位符解析器,使用environment去解析占位符
- if (!beanFactory.hasEmbeddedValueResolver()) {
- beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
- }
-
- // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
- // 加载时植入
- String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
- for (String weaverAwareName : weaverAwareNames) {
- getBean(weaverAwareName);
- }
-
- // Stop using the temporary ClassLoader for type matching.
- beanFactory.setTempClassLoader(null);
-
- // Allow for caching all bean definition metadata, not expecting further changes.
- beanFactory.freezeConfiguration();
-
- // Instantiate all remaining (non-lazy-init) singletons.
- // 初始化非懒加载的单例Bean
- beanFactory.preInstantiateSingletons();
- }
流程总结:
finishRefresh();方法
- protected void finishRefresh() {
- // Clear context-level resource caches (such as ASM metadata from scanning).
- clearResourceCaches();
-
- // Initialize lifecycle processor for this context.
- // 设置lifecycleProcessor,默认为DefaultLifecycleProcessor
- // 初始化容器的上下文生命周期
- // 容器启动完成后会去调start方法,停止会去调stop方法(但是必须isRunning返回true)
- initLifecycleProcessor();
-
- // Propagate refresh to lifecycle processor first.
- // 调用LifecycleBean的start()
- getLifecycleProcessor().onRefresh();
-
- // Publish the final event.
- // 发布容器刷新完所有事件
- publishEvent(new ContextRefreshedEvent(this));
-
- // Participate in LiveBeansView MBean, if active.
- if (!NativeDetector.inNativeImage()) {
- LiveBeansView.registerApplicationContext(this);
- }
- }
流程总结:
至此整个Spring容器就启动完成。
更多详情请关注---Java从零到壹
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。