invokeBeanFactoryPostProcessors(beanFactory)
- 代码段
- 调用所有注册的处理器
- 主要代码逻辑:PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors
- BeanDefinitionRegistryPostProcessor:
- BeanDefinitionRegistryPostProcessor是对BeanFactoryPostProcessor的拓展
- BeanDefinitionRegistryPostProcessor优先级更高
- BeanDefinitionRegistryPostProcessor可以注册进一步的bean定义,通过这些定义来进一步定义BeanFactoryPostProcessor
- BeanDefinitionRegistry:bean定义注册的规范的标准接口
public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory,List<BeanFactoryPostProcessor> beanFactoryPostProcessors){ // 所有已经执行的PostProcessors都会在这,用于防止重复执行 Set<String> processedBeans=new HashSet<>(); //判断当前工厂是否与BeanDefinitionRegistry(bean定义的注册接口)存在关联 if(beanFactory instanceof BeanDefinitionRegistry){ BeanDefinitionRegistry registry=(BeanDefinitionRegistry)beanFactory; //普通BeanFactoryPostProcessor的list List<BeanFactoryPostProcessor> regularPostProcessors=new ArrayList<>(); //高优先级BeanDefinitionRegistryPostProcessor的list List<BeanDefinitionRegistryPostProcessor> registryProcessors=new ArrayList<>(); for(BeanFactoryPostProcessor postProcessor:beanFactoryPostProcessors){ //对于优先级更高的BeanDefinitionRegistryPostProcessor加入 if(postProcessor instanceof BeanDefinitionRegistryPostProcessor){ BeanDefinitionRegistryPostProcessor registryProcessor= (BeanDefinitionRegistryPostProcessor)postProcessor; //通过构建者模式建造元数据共享器的定义,最终将元数据共享器的定义注册到BeanDefinitionRegistryPostProcessor registryProcessor.postProcessBeanDefinitionRegistry(registry); //将BeanFactoryPostProcessor中高优先级的BeanDefinitionRegistryPostProcessors加入list registryProcessors.add(registryProcessor); } else{ //将普通的BeanFactoryPostProcessor加入到list regularPostProcessors.add(postProcessor); } } List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors=new ArrayList<>(); //通过beanFactory匹配所有与(高优先级)BeanDefinitionRegistryPostProcessor存在联系的beanName并且转化为数组 String[]postProcessorNames= beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false); for(String ppName:postProcessorNames){ //对匹配之后的数组进行二次匹配,是否实现了优先级序列接口 if(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){ //这个地方的getBean有操作,这里不细说???? currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class)); //加入Set集合 processedBeans.add(ppName); } } //对currentRegistryProcessors进行排序 sortPostProcessors(currentRegistryProcessors,beanFactory); //将排序后的list加入registryProcessors registryProcessors.addAll(currentRegistryProcessors); //这个当然就是执行相关逻辑呀,具体是啥我也不知道,但是跟@Configration,@Bean......有关 //认为是对于PostProcessors的处理,将PostProcessors定义成为bean invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors,registry); //清除缓存 currentRegistryProcessors.clear(); //从BeanFactory加载BeanDefinitionRegistryPostProcessor的bean集合 postProcessorNames=beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false); for(String ppName:postProcessorNames){ //对集合进行筛选,实现了Ordered接口的进行处理 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(); //最后,对优先级最低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(); } //在@Configuration类中声明的任何Bean方法都必须在任何其他BeanFactoryPostProcessor执行之前注册其相应的 bean 定义, invokeBeanFactoryPostProcessors(registryProcessors,beanFactory); //这是低优先级处理,这里对Environment进行了处理 invokeBeanFactoryPostProcessors(regularPostProcessors,beanFactory); } else{ // 如果没有实现<br>bean定义的注册接口<br> invokeBeanFactoryPostProcessors(beanFactoryPostProcessors,beanFactory); } //获取beanFactory实现了BeanFactoryPostProcessor(低优先级PostProcessor)的beanName,实现了BeanFactoryPostProcessor String[]postProcessorNames= beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class,true,false); //将过滤后的beanFactory数组分为三个级别 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); } } // 先处理(高优先级) PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors,beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors,beanFactory); // 在处理(低优先级) 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); // 最后处理 没有优先级的. 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(); }
- invokeBeanFactoryPostProcessors中主要做了以下几件事事情
- 将BeanFactory中的所有已经注册了bean定义的bean分为两类:
- 高优先级(BeanDefinitionRegistryPostProcessor)类
- 低优先级(BeanFactoryPostProcessor)类
- 对上述两类的所有bean进行了处理,分为了三个等级priorityOrdered,ordered,nonOrdered(优先级依次递减);
- 调用了所有BeanFactory的处理器,并且对配置类@Configuration以及@Bean进行了处理
registerBeanPostProcessors(beanFactory)
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory,AbstractApplicationContext applicationContext){ //通过getBeanNamesForType获取beanFactory中与BeanPostProcessor存在联系的beanName String[]postProcessorNames=beanFactory.getBeanNamesForType(BeanPostProcessor.class,true,false); //注册BeanPostProcessorChecker int beanProcessorTargetCount=beanFactory.getBeanPostProcessorCount()+1+postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory,beanProcessorTargetCount)); //将实现了PriorityOrdered、Ordered接口的BeanPostProcessors分开处理 List<BeanPostProcessor> priorityOrderedPostProcessors=new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors=new ArrayList<>(); List<String> orderedPostProcessorNames=new ArrayList<>(); List<String> nonOrderedPostProcessorNames=new ArrayList<>(); for(String ppName:postProcessorNames){ //bean实现了PriorityOrdered if(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){ BeanPostProcessor pp=beanFactory.getBean(ppName,BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); //且bean实现了MergedBeanDefinitionPostProcessor if(pp instanceof MergedBeanDefinitionPostProcessor){ internalPostProcessors.add(pp); } } //bean实现了Ordered else if(beanFactory.isTypeMatch(ppName,Ordered.class)){ orderedPostProcessorNames.add(ppName); } //都没有实现 else{ nonOrderedPostProcessorNames.add(ppName); } } //对priorityOrderedPostProcessors的list进行排序 sortPostProcessors(priorityOrderedPostProcessors,beanFactory); //this.beanPostProcessors.add(beanPostProcessor);将BeanPostProcessor添加到list的队尾 registerBeanPostProcessors(beanFactory,priorityOrderedPostProcessors); // 对实现了Ordered接口的bean进行处理. 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); } } //排序order的list sortPostProcessors(orderedPostProcessors,beanFactory); //注册BeanPostProcessors,加入队尾 registerBeanPostProcessors(beanFactory,orderedPostProcessors); //最后,对普通的BeanPostProcessor进行处理 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); sortPostProcessors(internalPostProcessors,beanFactory); registerBeanPostProcessors(beanFactory,internalPostProcessors); //这里注册了ApplicationListenerDetector,但是不知道干嘛 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); } • registerBeanPostProcessors的关键逻辑代码 public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor){ //bean的处理器不能为空 Assert.notNull(beanPostProcessor,"BeanPostProcessor must not be null"); // 去除旧的beanPostProcessor this.beanPostProcessors.remove(beanPostProcessor); //是否开启 //添加实例化前回调的BeanPostProcessor子接口,以及实例化后但在设置显式属性或发生自动装配之前的回调 //用于抑制特定目标 bean 的默认实例化 if(beanPostProcessor instanceof InstantiationAwareBeanPostProcessor){ this.hasInstantiationAwareBeanPostProcessors=true; } //是否开启 //添加销毁前回调的BeanPostProcessor的子接口. if(beanPostProcessor instanceof DestructionAwareBeanPostProcessor){ this.hasDestructionAwareBeanPostProcessors=true; } //为所有新增的beanPostProcessor置于队列尾部 this.beanPostProcessors.add(beanPostProcessor); }
initMessageSource()
- 初始化ConfigurableListableBeanFactory的MessageSources,如果不存在MessageSources,则注册单例MessageSources(没什么好说的,代码一眼真🚀️)
initApplicationEventMulticaster()
- 初始化ApplicationEventMulticaster,如果ConfigurableListableBeanFactory中没有定义,则注册单例SimpleApplicationEventMulticaster
onRefresh()
- 初始化Tomcat容器,并且启动
onRefresh->createWebServer
private void createWebServer(){ WebServer webServer=this.webServer; ServletContext servletContext=getServletContext(); if(webServer==null&&servletContext==null){ //或WebServer工厂 ServletWebServerFactory factory=getWebServerFactory(); //创建Web容器,并且启动Tomcat this.webServer=factory.getWebServer(getSelfInitializer()); //注册正常结束的单例bean getBeanFactory().registerSingleton("webServerGracefulShutdown", new WebServerGracefulShutdownLifecycle(this.webServer)); //注册web服务启动时结束的单例bean getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this,this.webServer)); } else if(servletContext!=null){ try{ getSelfInitializer().onStartup(servletContext); } catch(ServletException ex){ throw new ApplicationContextException("Cannot initialize servlet context",ex); } } initPropertySources(); }
createWebServer->getWebServer
- 创建,配置,初始化并且启动Tomcat容器
- 代码截图:
- 在getTomcatWebServer(tomcat)阶段进行了Tomcat的初始化以及启动
registerListeners()
- 这里主要是对listeners的注册,以及(如果存在早期listeners)广播的发布
protected void registerListeners(){ // 注册默认静态的listeners for(ApplicationListener<?> listener:getApplicationListeners()){ getApplicationEventMulticaster().addApplicationListener(listener); } //获取BeanFactory()中与ApplicationListener存在关联的bean的全类名 String[]listenerBeanNames=getBeanNamesForType(ApplicationListener.class,true,false); for(String listenerBeanName:listenerBeanNames){ getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } //事件发布 Set<ApplicationEvent> earlyEventsToProcess=this.earlyApplicationEvents; this.earlyApplicationEvents=null; //如果早期时间存在,则发布 if(!CollectionUtils.isEmpty(earlyEventsToProcess)){ for(ApplicationEvent earlyEvent:earlyEventsToProcess){ //交由多播器处理 getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
finishBeanFactoryInitialization(beanFactory);
- 初始化单例bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){ // 初始化属性抓换服务 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)); } //是否存在默认的bean值信息解析器(主要用于解析bean的注释信息) if(!beanFactory.hasEmbeddedValueResolver()){ //如果没有则注册一个默认的bean值解析器 beanFactory.addEmbeddedValueResolver(strVal->getEnvironment().resolvePlaceholders(strVal)); } //初始化LoadTimeWeaverAware的实例bean对象 String[]weaverAwareNames=beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,false,false); for(String weaverAwareName:weaverAwareNames){ getBean(weaverAwareName); } //停止使用ClassLoader临时解析bean类名 beanFactory.setTempClassLoader(null); //冻结bean的定义信息,自此bean的定义信息不希望发生变化 beanFactory.freezeConfiguration(); // 实例化所有支持非惰性初始化的bean beanFactory.preInstantiateSingletons(); }
- preInstantiateSingletons
- FactoryBean:如果一个bean实现了这个接口,它被用作一个对象的工厂来暴露,而不是直接作为一个将自己暴露的bean实例
- bean的存在有两总形式,一种是作为基础实例存在(只是一个单独存在的bean实例),一种是作为实例工厂存在(实例工厂支持bean创建的多种形式)
- SmartInitializingSingleton:在BeanFactory引导期间的单例预实例化阶段结束时触发的回调接口.这个接口可以由单例 bean 实现,以便在常规单例实例化算法之后执行一些初始化,避免意外早期初始化(例如来自ListableBeanFactory.getBeansOfType调用)的副作用. 从这个意义上说,** 它是InitializingBean的替代方案,它在bean 的本地构造阶段结束时立即触发**.
public void preInstantiateSingletons()throws BeansException{ if(logger.isTraceEnabled()){ logger.trace("Pre-instantiating singletons in "+this); } //加载bean定义的信息 List<String> beanNames=new ArrayList<>(this.beanDefinitionNames); //触发所有非惰性单例bean的初始化 for(String beanName:beanNames){ RootBeanDefinition bd=getMergedLocalBeanDefinition(beanName); //bean非抽象,非惰性,bean支持单例 if(!bd.isAbstract()&&bd.isSingleton()&&!bd.isLazyInit()){ //是否存在bean的复杂加载器 if(isFactoryBean(beanName)){ //这里区别 //如果是普通bean,则是以bean名字作为key //如果是复杂加载器,则以"&"+bean的名字作为key Object bean=getBean(FACTORY_BEAN_PREFIX+beanName); if(bean instanceof FactoryBean){ FactoryBean<?> factory=(FactoryBean<?>)bean; boolean isEagerInit; //对FactoryBean进行鉴定,是否支持立即初始化 //SmartFactoryBean是对FactoryBean的拓展 //至于这段代码,看不懂 if(System.getSecurityManager()!=null&&factory instanceof SmartFactoryBean){ isEagerInit=AccessController.doPrivileged( (PrivilegedAction<Boolean>)((SmartFactoryBean<?>)factory)::isEagerInit, getAccessControlContext()); } else{ //默认不希望bean急切的实例化 isEagerInit=(factory instanceof SmartFactoryBean&& ((SmartFactoryBean<?>)factory).isEagerInit()); } //如果bean是FactoryBean且支持急切的实例化,则将bean急切的初始化 if(isEagerInit){ getBean(beanName); } } } else{ //如果bean是普通的bean,实例化普通bean getBean(beanName); } } } //bean初始化后之后的回调操作 for(String beanName:beanNames){ Object singletonInstance=getSingleton(beanName); if(singletonInstance instanceof SmartInitializingSingleton){ SmartInitializingSingleton smartSingleton=(SmartInitializingSingleton)singletonInstance; if(System.getSecurityManager()!=null){ AccessController.doPrivileged((PrivilegedAction<Object>)()->{ smartSingleton.afterSingletonsInstantiated(); return null; },getAccessControlContext()); } else{ smartSingleton.afterSingletonsInstantiated(); } } } }
finishRefresh
protected void finishRefresh(){ //清除此资源加载器中的所有资源缓存 clearResourceCaches(); //初始化Lifecycle initLifecycleProcessor(); //根据Lifecycle不同的阶段执行不同的start getLifecycleProcessor().onRefresh(); //对event进行装饰,广播发布所有事件 publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext(this); } finishRefresh->initLifecycleProcessor • LifecycleProcessor:用于在ApplicationContext中处理生命周期bean的策略接口 protected void initLifecycleProcessor(){ ConfigurableListableBeanFactory beanFactory=getBeanFactory(); //beanFactory是否存在LIFECYCLE_PROCESSOR_BEAN_NAME的具体实现 //如果存在key为LIFECYCLE_PROCESSOR_BEAN_NAME的bean if(beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)){ //获取LifecycleProcessor.class的具体实现,并且赋予当前context this.lifecycleProcessor= beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME,LifecycleProcessor.class); if(logger.isTraceEnabled()){ logger.trace("Using LifecycleProcessor ["+this.lifecycleProcessor+"]"); } } //如果beanFactory不存在key为LIFECYCLE_PROCESSOR_BEAN_NAME的LifecycleProcessor.class的具体实现 else{ //LifecycleProcessor的默认策略实现 DefaultLifecycleProcessor defaultProcessor=new DefaultLifecycleProcessor(); defaultProcessor.setBeanFactory(beanFactory); //将当前context的LifecycleProcessor使用默认的DefaultLifecycleProcessor //注册默认LifecycleProcessor为单例bean this.lifecycleProcessor=defaultProcessor; beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME,this.lifecycleProcessor); if(logger.isTraceEnabled()){ logger.trace("No '"+LIFECYCLE_PROCESSOR_BEAN_NAME+"' bean, using "+ "["+this.lifecycleProcessor.getClass().getSimpleName()+"]"); } } }
getLifecycleProcessor().onRefresh()
- SmartLifecycle:对于ApplicationContext中希望刷新或者以特定顺序关闭的Lifecycle接口的扩展
- 参数详情:
- isAutoStartup():对象是否应在上下文刷新时启动
- 如果此Lifecycle组件应在包含的ApplicationContext被刷新时由容器自动启动,则返回true
- 值为false表示该组件旨在通过显式Lifecycle.start()调用来启动
- Phased:指示此Lifecycle组件应启动和停止的阶段.启动过程从最低的相位值开始,以最高的相位值结束;关闭过程将应用相反的顺序
private void startBeans(boolean autoStartupOnly){ //获取上一阶段的所有LifecycleBean Map<String, Lifecycle> lifecycleBeans=getLifecycleBeans(); Map<Integer, LifecycleGroup> phases=new HashMap<>(); //遍历所有LifecycleBeans lifecycleBeans.forEach((beanName,bean)->{ //值为false,则显示调用全部Lifecycle //返回为true或者只调用bean支持context刷新时启动的Lifecycle if(!autoStartupOnly||(bean instanceof SmartLifecycle&&((SmartLifecycle)bean).isAutoStartup())){ //获取bean的执行的阶段 int phase=getPhase(bean); LifecycleGroup group=phases.get(phase); //将LifecycleBean根据执行的阶段来进行分组 if(group==null){ group=new LifecycleGroup(phase,this.timeoutPerShutdownPhase,lifecycleBeans,autoStartupOnly); phases.put(phase,group); } group.add(beanName,bean); } }); if(!phases.isEmpty()){ List<Integer> keys=new ArrayList<>(phases.keySet()); //按照阶段值进行排序 Collections.sort(keys); for(Integer key:keys){ //通过阶段值的排序执行不同的Lifecycle的start() phases.get(key).start(); } } }