• Spring注解开发(七)Spring容器创建


    简单看一下Spring IOC容器创建的步骤:
    注解相关的Spring容器为AnnotationConfigApplicationContext 。

    下图是AnnotationConfigApplicationContext的主要实现及继承类图:
    在这里插入图片描述
    从图中可以看到:

    • AnnotationConfigApplicationContext继承GenericApplicationContext这个通用应用上下文,GenericApplicationContext内部定义了一个DefaultListableBeanFactory实例。
    • GenericApplicationContext实现了BeanDefinitionRegistry接口,所以可以通过AnnotationConfigApplicationContext实例注册bean defintion,然后调用refresh()方法来初始化上下文。
    	@Override
    	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
    			throws BeanDefinitionStoreException {
    
    		this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
    	}
    
    • AnnotationConfigApplicationContext继承AbstractApplicationContext,AbstractApplicationContext提供了ApplicationContext的抽象实现。

    从new AnnotationConfigApplicationContext简单示例查看Spring容器创建过程。

      AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
    
    //创建一个AnnotationConfigApplicationContext,从给定的一个或多个带注释的类,例如 {@Configuration}类获取bean定义信息并自动刷新上下文。 
    public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
           //初始化bean读取器和扫描器;
           //调用父类GenericApplicationContext无参构造函数,初始化一个BeanFactory: DefaultListableBeanFactory beanFactory = new  DefaultListableBeanFactory()
    		this();
    		//注册配置类,此处annotatedClasses为ExtConfig.class
    		register(annotatedClasses);
    		//刷新容器上下文
    		refresh();
    	}
    

    This方法

    	public AnnotationConfigApplicationContext() {
    	    //在IOC容器中初始化一个 注解bean读取器AnnotatedBeanDefinitionReader
    		this.reader = new AnnotatedBeanDefinitionReader(this);
    		//在IOC容器中初始化一个 按类路径扫描注解bean的 扫描器
    		this.scanner = new ClassPathBeanDefinitionScanner(this);
    	}
    

    AnnotationConfigApplicationContext继承自AbstractApplicationContext,会先调用AbstractApplicationContext的构造函数,初始化一个DefaultListableBeanFactory

    public GenericApplicationContext() {
            //初始化BeanFactory
    		this.beanFactory = new DefaultListableBeanFactory();
    	}
    

    看一下new AnnotatedBeanDefinitionReader(this)的实现,源码如下:

    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);
    		//此处向容器中注册了很多基础的的处理器,比如像refresh第5步的ConfigurationClassPostProcessor就是在此处注册的,还有第六步的AutowiredAnnotationProcessor等
    		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    	}
    

    register方法

    在这里插入图片描述
    如上Debug路径,最终调用的为AnnotatedBeanDefinitionReader的doRegisterBean方法:
    此处向容器中注册

    <T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
    			@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
            //将Bean配置类信息包装为AnnotatedGenericBeanDefinition对象
            //在此构造方法中新建了一个StandardAnnotationMetadata将配置类的注解信息属性赋值给AnnotatedGenericBeanDefinition的属性metadata
    		AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
    		//判断@Conditional装配条件是否需要跳过注册
    		if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
    			return;
    		}
    
    		abd.setInstanceSupplier(instanceSupplier);
    		 //解析bean作用域(singleton),如果有@Scope注解则解析@Scope,没有则取默认值singleton
    		ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
    		//设置作用域,此处取默认singleton
    		abd.setScope(scopeMetadata.getScopeName());
    		//获取beanName,如果没有则生成类名首字母小写作为beanName
    		String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
           //处理通用定义注解,有这几个:Lazy;Primary;DependsOn;Role;Description
    		AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
    		//@Qualifier处理
    		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));
    				}
    			}
    		}
    		for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
    			customizer.customize(abd);
    		}
            //根据beanName和beanDefinition封装一个beanhold,持有具有名称和别名的BeanDefinition。
    		BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
    		//创建代理对象beanDefinition,此处scopedProxyMode为ScopedProxyMode.NO,原样返回
    		definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
    		/*向BeanFactory注册该beanDefinition,将beanDefinition注册到容器中
    		 *this.beanFactory.registerBeanDefinition(beanName, beanDefinition);
    		 *----调用到DefaultListableBeanFactory的registerBeanDefinition方法
    		 *将beanName和beanDefinition放到其内部维护的一个Map,并将beanName放到List集合中
    		 *this.beanDefinitionMap.put(beanName, beanDefinition);
    		 *this.beanDefinitionNames.add(beanName);
    		 */
    		BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
    	}
    

    从上可以看到register方法完成了配置类的解析和注册。

    refresh方法

    refresh方法在AbstractApplicationContext被调用,源码如下:

    	@Override
    	public void refresh() throws BeansException, IllegalStateException {
    		synchronized (this.startupShutdownMonitor) {
    			//1.刷新前的预处理
    			prepareRefresh();
    			//2.获取BeanFactory;默认实现是DefaultListableBeanFactory,在创建容器的时候创建的
    			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    			//3. BeanFactory的预准备工作(BeanFactory进行一些设置)
    			prepareBeanFactory(beanFactory);
    			try {
    				// 4.BeanFactory准备工作完成后进行的后置处理工作
    				postProcessBeanFactory(beanFactory);
    				// 5.执行BeanFactoryPostProcessor的方法
    				invokeBeanFactoryPostProcessors(beanFactory);
    				//6.注册BeanPostProcessor(Bean的后置处理器)
    				registerBeanPostProcessors(beanFactory);
    				// 7.初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
    				initMessageSource();
    				// 8.初始化事件派发器
    				initApplicationEventMulticaster();
    				// 9.留给子容器(子类),子类重写这个方法,在容器刷新的时候可以自定义逻辑
    				onRefresh();
    				// 10.给容器中将所有项目里面的ApplicationListener注册进来
    				registerListeners();
    				// 11.初始化所有剩下的单实例bean
    				finishBeanFactoryInitialization(beanFactory);
    				// 12.完成BeanFactory的初始化创建工作;IOC容器就创建完成,发布容器创建完成事件
    				finishRefresh();
    			}
    		........
    		}
    	}
    

    1. prepareRefresh()刷新前的预处理

    	protected void prepareRefresh() {
    		// 启动时间
    		this.startupDate = System.currentTimeMillis();
            //设置启动标识
    		this.closed.set(false);
    		this.active.set(true);
            ......
    		// 初始化在上下文环境中的占位符属性源.
    		//初始化一些属性设置;空方法由子类自定义个性化的属性设置方法;
    		initPropertySources();
    		// 检验属性合法性,是否不为空等
    		getEnvironment().validateRequiredProperties();
    
    		// 创建保存容器早期事件监听的容器
    		if (this.earlyApplicationListeners == null) {
    			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    		}
            .....
    		//保存容器中的一些早期的事件,将在多播器可用时发布
    		this.earlyApplicationEvents = new LinkedHashSet<>();
    	}
    
    • 设置启动标识,容器状态设置
    • 初始化在上下文环境中的占位符属性源.
    • 当前环境的一些校验等.

    2. obtainFreshBeanFactory获取BeanFactory

    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    		refreshBeanFactory();
    		return getBeanFactory();
    	}
    
    • refreshBeanFactory()
    protected final void refreshBeanFactory() throws IllegalStateException {
           //设置刷新标识为true
    		if (!this.refreshed.compareAndSet(false, true)) {
    			throw new IllegalStateException(
    					"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
    		}
    		//设置序列化编码
    		this.beanFactory.setSerializationId(getId());
    	}
    
    • getBeanFactory()
    @Override
    	public final ConfigurableListableBeanFactory getBeanFactory() {
    	//返回默认创建的DefaultListableBeanFactory
    		return this.beanFactory;
    	}
    
    • 设置容器刷新标识为true
    • 获取DefaultListableBeanFactory

    3. prepareBeanFactory BeanFactory的预准备工作

    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		// 设置beanFactory使用当前上下文的类加载器等。
    		beanFactory.setBeanClassLoader(getClassLoader());
    		//设置beanFactory的表达式处理器,内部创建了一个SpelExpressionParser用于处理#{**}
    		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    		//为beanFactory增加一个默认的PropertyEditor,更准确应该是属性转换器,比如从String到Date类型的转化
    		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    
    		// 添加ApplicationContextAwareProcessor
    		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    		//设置几个忽略自动装配的接口
    		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、ResourceLoader、ApplicationEventPublisher、ApplicationContext
            //其他组件中可以通过 @autowired 直接注册使用
    		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    		beanFactory.registerResolvableDependency(ApplicationContext.class, this);
    
    		// 添加BeanPostProcessor后置处理器,在bean初始化前后的一些工作
    		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
    
    		// 如果包含LoadTimeWeaver,(AspectJ支持)
    		if (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()));
    		}
    		//注册默认的environment
    		//environment
    		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
    			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    		}
    		//systemProperties
    		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
    			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    		}
    		//systemEnvironment
    		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
    			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    		}
    	}
    

    -设置beanFactory的各种属性

    4. postProcessBeanFactory(beanFactory) BeanFactory后置处理

    //在AbstractApplicationContext里是空实现,该方法交由子类覆盖去实现
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    	}
    

    看一下两个子类的实现:

    • GenericWebApplicationContext
    	/**
    	 * 注册ServletContextAwareProcessor.
    	 * @see ServletContextAwareProcessor
    	 */
    	@Override
    	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		if (this.servletContext != null) {
    		    //添加ServletContextAwareProcessor到beanFactory容器中
    			beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext));
    			//忽略装配接口ServletContextAware
    			beanFactory.ignoreDependencyInterface(ServletContextAware.class);
    		}
            //注册WEB应用特定的scope到 beanFactory 中
    		WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
    		//注册WEB应用特定的Environment bean到beanFactory中
    		WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext);
    	}
    
    • AbstractRefreshableWebApplicationContext
    	@Override
    	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        	//添加ServletContextAwareProcessor到beanFactory容器中
    		beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
    		//忽略装配接口ServletContextAware和ServletConfigAware
    		beanFactory.ignoreDependencyInterface(ServletContextAware.class);
    		beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
            //注册WEB应用特定的scope到 beanFactory 中
    		WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
    		//注册WEB应用特定的Environment bean到beanFactory中
    		WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
    	}
    

    5.invokeBeanFactoryPostProcessors 执行BeanFactory后置处理器

    先介绍两个接口:

    • BeanFactoryPostProcessor:用来修改Spring容器中已经存在的bean的定义,使用ConfigurableListableBeanFactory对bean进行处理
    • BeanDefinitionRegistryPostProcessor:继承BeanFactoryPostProcessor,作用跟BeanFactoryPostProcessor一样,只不过是使用BeanDefinitionRegistry对bean进行处理
      在Spring容器中找出实现了BeanFactoryPostProcessor接口的processor并执行。Spring容器会委托给PostProcessorRegistrationDelegate的invokeBeanFactoryPostProcessors方法执行。

    注:

    1. 在springboot的web程序初始化AnnotationConfigServletWebServerApplicationContext容器时,会初始化内部属性AnnotatedBeanDefinitionReader reader,这个reader构造的时候会在BeanFactory中注册一些post processor,包括BeanPostProcessor和BeanFactoryPostProcessor(比如ConfigurationClassPostProcessor、AutowiredAnnotationBeanPostProcessor)。
    AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    
    1. 在使用mybatis时,一般配置了MapperScannerConfigurer的bean,这个bean就是继承的BeanDefinitionRegistryPostProcessor,所以也是这个地方把扫描的mybatis的接口注册到容器中的。

    接下来看invokeBeanFactoryPostProcessors做了什么:

    //beanFactoryPostProcessors此处(一般)为空,后序会通过类型获取
    public static void invokeBeanFactoryPostProcessors(
    			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
    		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
    		Set<String> processedBeans = new HashSet<>();
            //判断是否为BeanDefinitionRegistry类型
    		if (beanFactory instanceof BeanDefinitionRegistry) {
         		//强转
    			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
    			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
               
    			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
    				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
    					BeanDefinitionRegistryPostProcessor registryProcessor =
    							(BeanDefinitionRegistryPostProcessor) postProcessor;
    					//调用重写的postProcessBeanDefinitionRegistry方法
    					registryProcessor.postProcessBeanDefinitionRegistry(registry);
    					//添加到集合中
    					registryProcessors.add(registryProcessor);
    				}
    				else {
    				    //如果不是BeanDefinitionRegistryPostProcessor类型,则添加到regularPostProcessors集合
    					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.
    			//用于保存临时的BeanDefinitionRegistryPostProcessor
    			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
    
    			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
    			//首先从容器中获取BeanDefinitionRegistryPostProcessor类型的postProcessorNames 
    			/* Spring有一个内部的BeanFactoryPostProcessor 
    			 * ID:org.springframework.context.annotation.internalConfigurationAnnotationProcessor;
    		     * 类型为BeanDefinitionRegistryPostProcessor,实现类为ConfigurationClassPostProcessor;
    		     * 负责解析处理所有@Configuration标签类,并将Bean定义注册到BeanFactory中
    		    */
    			String[] postProcessorNames =
    					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
               //此处postProcessorNames长度为1,ppName为
    			for (String ppName : postProcessorNames) {
    			//先处理实现PriorityOrdered(优先级)接口的
    				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    				   //创建了ConfigurationClassPostProcessor类,并放入集合
    					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
    					processedBeans.add(ppName);
    				}
    			}
    			//按照优先级排序
    			sortPostProcessors(currentRegistryProcessors, beanFactory);
    			//添加到集合中
    			registryProcessors.addAll(currentRegistryProcessors);
    			//执行所有存储在currentRegistryProcessors中的后置方法postProcessBeanDefinitionRegistry
    			//在此处执行ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法,处理    Component,PropertySources,ComponentScans等,并注册beanDefinition到容器中
    			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    			//清空临时集合
    			currentRegistryProcessors.clear();
    
    			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
    			//执行实现了Ordered接口的BeanDefinitionRegistryPostProcessor
    			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    			for (String ppName : postProcessorNames) {
    				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);
    			currentRegistryProcessors.clear();
    
    			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
    			//最后处理剩下的BeanDefinitionRegistryPostProcessors 
    			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);
    				currentRegistryProcessors.clear();
    			}
    
    			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
    			//执行子类实现的postProcessBeanFactory方法
    			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    		}
    
    		else {
    			// Invoke factory processors registered with the context instance.
    			//如果不是BeanDefinitionRegistry 只需要调用其回调函数(postProcessBeanFactory())即可
    			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    		}
    
    		// Do not initialize FactoryBeans here: We need to leave all regular beans
    		// uninitialized to let the bean factory post-processors apply to them!
    		//获取BeanFactoryPostProcessor类型
    		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
    			}
    			//实现了PriorityOrdered接口的被放入优先级集合
    			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    			}
    			//实现了Ordered接口
    			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    				orderedPostProcessorNames.add(ppName);
    			}
    			else {
    		     	//其他类型的
    				nonOrderedPostProcessorNames.add(ppName);
    			}
    		}
    
    		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    		//根据优先级排序
    		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    		//先执行实现了PriorityOrdered接口的
    		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    
    		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
    		for (String postProcessorName : orderedPostProcessorNames) {
    			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    		}
    		sortPostProcessors(orderedPostProcessors, beanFactory);
    		//执行实现了Ordered接口的
    		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    
    		// Finally, invoke all other BeanFactoryPostProcessors.
    		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    		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();
    	}
    

    6. registerBeanPostProcessors 注册BeanPostProcessor

    进入PostProcessorRegistrationDelegate类的registerBeanPostProcessors方法,源码如下:

    public static void registerBeanPostProcessors(
    			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
            //获取所有BeanPostProcessor类型的beanName
            //此处获取了org.springframework.context.annotation.internalAutowiredAnnotationProcessor(AutowiredAnnotationProcessor)和
            //org.springframework.context.annotation.internalCommonAnnotationProcessor(CommonAnnotationBeanPostProcessor )
    		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.
    		//获取所有的beanPostProcessor数量
    		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    		//注册BeanPostProcessorChecker,其主要的作用是在bean的实例化期间进行日志的记录
    		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<>();
    		//按照优先级和内部Bean放入各个集合
    		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);
    		//处理实现了PriorityOrdered接口的
    		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
    
    		// Next, register the BeanPostProcessors that implement Ordered.
    		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
    		for (String ppName : orderedPostProcessorNames) {
         		//创建实例对象
    			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
    			orderedPostProcessors.add(pp);
    			if (pp instanceof MergedBeanDefinitionPostProcessor) {
    				internalPostProcessors.add(pp);
    			}
    		}
    		sortPostProcessors(orderedPostProcessors, beanFactory);
    		//处理实现了Ordered接口的
    		registerBeanPostProcessors(beanFactory, orderedPostProcessors);
    
    		// Now, register all regular BeanPostProcessors.
    		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    		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.
    		sortPostProcessors(internalPostProcessors, beanFactory);
    		//最后处理所有的内部的BeanPostProcessors
    		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
    		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
    	}
    

    7. initMessageSource 初始化MessageSource组件

    protected void initMessageSource() {
            //获取BeanFactory
    		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    		//查找是否包含messageSource类
    		if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
    		   //获取该类的实例Bean
    			this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
    			// Make MessageSource aware of parent MessageSource.
    			//如果容器的parent属性不为空(此处为空)并且messageSource 是HierarchicalMessageSource类型
    			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.
    					//设置容器的ParentMessageSource,如果为空,则返回父容器本身
    					hms.setParentMessageSource(getInternalParentMessageSource());
    				}
    			}
    			if (logger.isTraceEnabled()) {
    				logger.trace("Using MessageSource [" + this.messageSource + "]");
    			}
    		}
    		else {
    			// Use empty MessageSource to be able to accept getMessage calls.
    			使用空的MessageSource去接受getMessage调用
    			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 + "]");
    			}
    		}
    	}
    

    8. initApplicationEventMulticaster 初始化事件派发器

    protected void initApplicationEventMulticaster() {
    		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
             //如果包含applicationEventMulticaster类型的bean	
    		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 + "]");
    			}
    		}
    		else {
    		    //没有则新建一个SimpleApplicationEventMulticaster,并注册。
    			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() + "]");
    			}
    		}
    	}
    

    9. onRefresh 容器刷新自定义逻辑

    	protected void onRefresh() throws BeansException {
    		// For subclasses: do nothing by default.
    	}
    

    一个模板方法,不同的Spring容器做不同的事情。
    比如SpringBoot的web程序的容器ServletWebServerApplicationContext中会调用createWebServer方法去创建内置的Servlet容器。

    	@Override
    	protected void onRefresh() {
    		super.onRefresh();
    		try {
    			createWebServer();
    		}catch (Throwable ex) {
    			throw new ApplicationContextException("Unable to start web server", ex);
    		}
    	}
    

    10.registerListeners 注册ApplicationListener

    protected void registerListeners() {
    		// Register statically specified listeners first.
    		//注册静态指定的listeners 。
    		//获取ApplicationListeners并注册到事件派发器上(此处为空)
    		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!
    		//获取所有ApplicationListener类型的BeanName,并添加到事件派发器上
    		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...
    		//此处发布早期的容器事件(此处为空)
    		Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    		this.earlyApplicationEvents = null;
    		if (earlyEventsToProcess != null) {
    			for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
                   //执行onApplication方法
    				getApplicationEventMulticaster().multicastEvent(earlyEvent);
    			}
    		}
    	
    

    11. finishBeanFactoryInitialization 初始化剩下的单实例bean(非Lazy)

    实例化BeanFactory中已经被注册但是未实例化的所有实例(懒加载的不需要实例化)。比如invokeBeanFactoryPostProcessors方法中根据各种注解解析出来的类,在这个时候都会被初始化。实例化的过程各种BeanPostProcessor开始起作用。

    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    		// Initialize conversion service for this context.
    		//为bean工厂设置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 bean post-processor
    		// (such as a PropertyPlaceholderConfigurer bean) registered any before:
    		// at this point, primarily for resolution in annotation attribute values.
    		//如果beanFactory之前没有注册嵌入值解析器,则注册默认的嵌入值解析器:主要用于注解属性值的解析
    		if (!beanFactory.hasEmbeddedValueResolver()) {
    			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    		}
    
    		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    		//初始化LoadTimeWeaverAware类型对象(此处为空)
    		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    		for (String weaverAwareName : weaverAwareNames) {
    			getBean(weaverAwareName);
    		}
    		// Stop using the temporary ClassLoader for type matching.
    		//将临时的Classloader置为空
    		beanFactory.setTempClassLoader(null);
    		// Allow for caching all bean definition metadata, not expecting further changes.
    		//把bean定义元数据信息保存,下一步将实例化Bean,不希望再有其他变动
    		beanFactory.freezeConfiguration();
    		// Instantiate all remaining (non-lazy-init) singletons.
    		//实例化所有剩下的非lazy的单例Bean
    		beanFactory.preInstantiateSingletons();
    	}
    
    beanFactory.preInstantiateSingletons()源码如下:
    @Override
    	public void preInstantiateSingletons() throws BeansException {
    		if (logger.isTraceEnabled()) {
    			logger.trace("Pre-instantiating singletons in " + this);
    		}
    
    		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
    		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    		//获取BeanNames
    		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    
    		// Trigger initialization of all non-lazy singleton beans...
    		//遍历并实例化Bean
    		for (String beanName : beanNames) {
    		    //获取Bean定义信息
    			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    			//判断不是抽象,懒加载并且是单例的Bean进入下面创建环节
    			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
    				//判断是否为FactoryBean
    				if (isFactoryBean(beanName)) {
    				    //获取FactoryBean(在Spring注解开发第一章中有说明&获取的是FactoryBean本身)
    					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
    					if (bean instanceof FactoryBean) {
    						final FactoryBean<?> factory = (FactoryBean<?>) bean;
    						boolean isEagerInit;
    						//判断是否需要急切的被初始化
    						if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
    							isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
    											((SmartFactoryBean<?>) factory)::isEagerInit,
    									getAccessControlContext());
    						}
    						else {
    							isEagerInit = (factory instanceof SmartFactoryBean &&
    									((SmartFactoryBean<?>) factory).isEagerInit());
    						}
    						if (isEagerInit) {
    							getBean(beanName);
    						}
    					}
    				}
    				else {
    				//如果beanName对应的bean不是FactoryBean,通过beanName获取bean实例
    					getBean(beanName);
    				}
    			}
    		}
    
    		// Trigger post-initialization callback for all applicable beans...
    		for (String beanName : beanNames) {
    			Object singletonInstance = getSingleton(beanName);
    			if (singletonInstance instanceof SmartInitializingSingleton) {
    				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
    				if (System.getSecurityManager() != null) {
    					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    						smartSingleton.afterSingletonsInstantiated();
    						return null;
    					}, getAccessControlContext());
    				}
    				else {
    					smartSingleton.afterSingletonsInstantiated();
    				}
    			}
    		}
    	}
    

    12.finishRefresh 完成BeanFactory的初始化创建工作

    	protected void finishRefresh() {
    		// Clear context-level resource caches (such as ASM metadata from scanning).
    		//清空容器级别的缓存信息
    		clearResourceCaches();
    		// Initialize lifecycle processor for this context.
    		//初始化生命周期处理器,并设置到Spring容器中(LifecycleProcessor)
    		initLifecycleProcessor();
    		// Propagate refresh to lifecycle processor first.
    		//调用生命周期处理器的onRefresh方法,这个方法会找出Spring容器中实现了SmartLifecycle接口的类并进行start方法的调用
    		getLifecycleProcessor().onRefresh();
    		// Publish the final event.
    		//发布容器完成刷新时间
    		publishEvent(new ContextRefreshedEvent(this));
    		// Participate in LiveBeansView MBean, if active.
    		LiveBeansView.registerApplicationContext(this);
    	}
    
  • 相关阅读:
    Weblogic(CVE-2018-2894)
    WebLogic (CVE-2018-2628)
    WebLogic(CVE-2017-10271)
    DC-5靶机渗透
    DC-4靶机渗透
    DC-3靶机渗透
    DC-2靶机渗透
    时间戳倒计时
    服务器的一些Linux命令
    CCF试题清单
  • 原文地址:https://www.cnblogs.com/demo-alen/p/13547218.html
Copyright © 2020-2023  润新知