Spring系列(三):Spring IoC源码解析
2019-08-16 12:19:48来源:博客园 阅读 ()
Spring系列(三):Spring IoC源码解析
一、Spring容器类继承图
二、容器前期准备
IoC源码解析入口:
/** * @desc: ioc原理解析 启动 * @author: toby * @date: 2019/7/22 22:20 */ public class PrincipleMain { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrincipleConfig.class); } }
调用构造函数AnnotationConfigApplicationContext
调用this(),会默认先调用父类的无参构造函数,为ApplicationContext上下文对象初始beanFactory = new DefaultListableBeanFactory()
在调用当前类的this(),也就是调用自己的无参构造函数:
进到创建注解模式下的Bean定义读取器:
org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object) 主要是注册Spring自身的一些后置处理器
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, @Nullable Object source) { DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8); /** * 为我们容器中注册解析主配置类的后置处理器ConfigurationClassPostProcessor * beanName = org.springframework.context.annotation.internalConfigurationAnnotationProcessor */ 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)); } /** * 为我们容器中注册处理@Autowired注解的Bean的后置处理器AutowiredAnnotationBeanPostProcessor * beanName = org.springframework.context.annotation.internalAutowiredAnnotationProcessor */ 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)); } /** * 为我们容器中注册处理@Required属性注解的Bean后置处理器RequiredAnnotationBeanPostProcessor * beanName = org.springframework.context.annotation.internalRequiredAnnotationProcessor */ if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 为我们容器注册处理JSR规范注解的Bean后置处理器CommonAnnotationBeanPostProcessor * beanName = org.springframework.context.annotation.internalCommonAnnotationProcessor */ if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 为我们容器注册处理jpa的Bean的后置处理器org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor */ if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException ex) { throw new IllegalStateException( "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); } /** * 处理监听方法的注解解析器EventListenerMethodProcessor */ if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME)); } /** * 注册事件监听器工厂 */ if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME)); } return beanDefs; }
读取器初始化完成后,Spring的容器的Bean的定义信息就有Spring自身的一些后置处理器了,Debug如下:
读取器初始化完成后,接下来初始化ClassPath下的Bean定义扫描器:
org.springframework.context.annotation.ClassPathBeanDefinitionScanner#ClassPathBeanDefinitionScanner(org.springframework.beans.factory.support.BeanDefinitionRegistry, boolean, org.springframework.core.env.Environment, org.springframework.core.io.ResourceLoader) 类路径下的Bean定义扫描
org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters 注入默认的Filter
protected void registerDefaultFilters() { this.includeFilters.add(new AnnotationTypeFilter(Component.class)); ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader(); try { this.includeFilters.add(new AnnotationTypeFilter( ((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false)); logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning"); } catch (ClassNotFoundException ex) { // JSR-250 1.1 API (as included in Java EE 6) not available - simply skip. } try { this.includeFilters.add(new AnnotationTypeFilter( ((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false)); logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning"); } catch (ClassNotFoundException ex) { // JSR-330 API not available - simply skip. } }
这里需要注意的是为什么new AnnotationTypeFilter(Component.class)就可以处理@Repository,@Service,@Controller这3个注解,原因如下:
自此前期准备工作完成
三、org.springframework.context.support.AbstractApplicationContext#refresh 12大步
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //1:准备刷新上下文环境 prepareRefresh(); //2:获取初始化Bean工厂 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //3:对bean工厂进行填充属性 prepareBeanFactory(beanFactory); try { //4:Spring开放接口 留给子类去实现该接口 postProcessBeanFactory(beanFactory); //5:调用我们的bean工厂的后置处理器 invokeBeanFactoryPostProcessors(beanFactory); //6:注册我们bean后置处理器 registerBeanPostProcessors(beanFactory); //7:初始化国际化资源处理器 initMessageSource(); //8:初始化事件多播器 initApplicationEventMulticaster(); //9:这个方法同样也是留个子类实现,其中springboot也是从这个方法进行tomcat的启动 onRefresh(); //10:把我们的事件监听器注册到多播器上 registerListeners(); //11:实例化所有的非懒加载的单实例bean finishBeanFactoryInitialization(beanFactory); //12:最后刷新容器 发布刷新事件(Spring cloud eureka也是从这里启动的) 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(); } } }
第一步:prepareRefresh()
准备刷新上下文环境:
protected void prepareRefresh() { // Switch to active. this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); } /** * 初始化上下文环境 */ initPropertySources(); /** * 用来校验我们容器启动必须依赖的环境变量的值 */ getEnvironment().validateRequiredProperties(); /** * 创建一个早期事件监听器对象 */ 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); } /** * 创建一个容器用于保存早期待发布的事件集合 什么是早期事件了? * 就是我们的事件监听器还没有注册到事件多播器上的时候都称为早期事件 */ this.earlyApplicationEvents = new LinkedHashSet<>(); }
第二步:ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory()
获取初始化的Bean的工厂:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //刷新bean工厂() refreshBeanFactory(); //返回之前容器准备工作的时候创建的的bean工厂也就是DefaultListableBeanFactory(很重要) ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); } return beanFactory; }
org.springframework.context.support.GenericApplicationContext#refreshBeanFactory,注意只能刷一次
protected final void refreshBeanFactory() throws IllegalStateException { //由于BeanFactory只能刷新一次,多线程情况下可能导致线程安全问题,所有使用cas原子操作来保证 if (!this.refreshed.compareAndSet(false, true)) { throw new IllegalStateException( "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once"); } //指定Bean工厂的序列化Id this.beanFactory.setSerializationId(getId()); }
第三步:prepareBeanFactory(beanFactory)
对bean工厂进行填充属性:
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { //设置bean工厂的类加载器为当前application应用上下文的加载器 beanFactory.setBeanClassLoader(getClassLoader()); //为bean工厂设置SPEL表达式解析器对象StandardBeanExpressionResolver beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); //为我们的bean工厂设置了一个propertyEditor属性资源编辑器对象(用于后面的给bean对象赋值使用) beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); //注册ApplicationContextAwareProcessor后置处理器用来处理ApplicationContextAware接口的回调方法 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); /** * 当Spring将ApplicationContextAwareProcessor注册后,那么在invokeAwarelnterfaces方法中调用的Aware类已经不是普通的bean了 , * 如ResourceLoaderAware、ApplicationEventPublisherAware、ApplicationContextAware等,那么当然需要在Spring做bean的依赖注入的时候忽略它们。 * 这个就是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.class的解析依赖后, * 当bean的属性注入的时候,一旦检测到属性为BeanFactory类型便会将beanFactory的实例注入进去。 */ beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); //注册了一个事件监听器探测器后置处理器接口 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); 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())); } if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
第四步:postProcessBeanFactory(beanFactory)
Spring开放接口留给子类去实现该接口:主要用来改变BeanFactory比如给BeanFactory添加一些自己的BeanPostProcessor(Bean的后置处理器)
第五步:invokeBeanFactoryPostProcessors(beanFactory)
调用我们的bean工厂的后置处理器:详解见:Spring IoC源码解析之invokeBeanFactoryPostProcessors
第六步:registerBeanPostProcessors(beanFactory)
注册我们bean后置处理器:
org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)
/** * 往容器中注册了我们的bean的后置处理器 * bean的后置处理器在什么时候进行调用?在bean的生命周期中 * @param beanFactory * @param applicationContext */ public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { //去容器中获取所有的BeanPostProcessor的bean名称 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); /** * beanFactory.getBeanPostProcessorCount()获取的是已经添加在beanFactory的beanPostProcessors集合中的 * postProcessorNames.length beanFactory工厂中BeanPostProcessor个数 +1 又注册了BeanPostProcessorChecker的后置处理器 */ int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); /** * 按照BeanPostProcessor实现的优先级接口来分离我们的后置处理器 */ //保存实现了priorityOrdered接口的 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); //容器内部的 List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); //实现了我们ordered接口的 List<String> orderedPostProcessorNames = new ArrayList<>(); //实现了我们任何优先级的 List<String> nonOrderedPostProcessorNames = new ArrayList<>(); //循环我们的bean定义(BeanPostProcessor) for (String ppName : postProcessorNames) { //若实现了PriorityOrdered接口的 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { //显示的调用getBean流程创建bean的后置处理器 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); //加入到集合中 priorityOrderedPostProcessors.add(pp); //判断是否实现了MergedBeanDefinitionPostProcessor if (pp instanceof MergedBeanDefinitionPostProcessor) { //加入到集合中 internalPostProcessors.add(pp); } } //判断是否实现了Ordered else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } //把实现了priorityOrdered注册到容器中 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); //处理实现Ordered的bean后置处理器 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String ppName : orderedPostProcessorNames) { //显示调用getBean方法 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); //加入到集合中 orderedPostProcessors.add(pp); //判断是否实现了MergedBeanDefinitionPostProcessor if (pp instanceof MergedBeanDefinitionPostProcessor) { //加入到集合中 internalPostProcessors.add(pp); } } //排序并且注册我们实现了Order接口的后置处理器 sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // 实例化我们所有的非排序接口的 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String ppName : nonOrderedPostProcessorNames) { //显示调用 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); //判断是否实现了MergedBeanDefinitionPostProcessor if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } //注册我们普通的没有实现任何排序接口的 registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); //注册MergedBeanDefinitionPostProcessor类型的后置处理器 sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); //注册ApplicationListenerDetector应用监听器探测器的后置处理器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
第七步:initMessageSource()
初始化国际化资源处理器:
/** * Initialize the MessageSource. * Use parent's if none defined in this context. */ protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { 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. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isDebugEnabled()) { logger.debug("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.isDebugEnabled()) { logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME + "': using default [" + this.messageSource + "]"); } } }
第八步:initApplicationEventMulticaster()
初始化事件多播器:
/** * 从bean工厂中获取或者直接显示的new一个事件多播器赋值给applicatoinContext对象的applicationEventMulticaster属性 * 事件多播器采用典型的设计模式就是观察者模式 多播器作为的是一个被观察者 * @see org.springframework.context.event.SimpleApplicationEventMulticaster */ protected void initApplicationEventMulticaster() { //获取我们的bean工厂对象 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //判断容器中是否包含了applicationEventMulticaster事件多播器组件 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { //直接显示的调用我们的getBean获取出来赋值给我们的applicationContext对象 this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } //容器中没有的话 else { //直接new一个 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); //并且注入到容器中 beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isDebugEnabled()) { logger.debug("Unable to locate ApplicationEventMulticaster with name '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "': using default [" + this.applicationEventMulticaster + "]"); } } }
第九步:onRefresh()
这个方法很重要同样也是留个子类实现,其中Spring Boot就是从这个方法进行tomcat的启动(后续讲Spring Boot的源码分析的时候会涉及到这块,比如:Spring容器的启动如何带动web容器tomcat的启动以及web容器tomcat的启动如何带动Spring容器的启动)
第十步:registerListeners()
把我们的事件监听器注册到事件多播器上:
protected void registerListeners() { //获取容器中所有的监听器对象 for (ApplicationListener<?> listener : getApplicationListeners()) { //把监听器挨个的注册到我们的事件多播器上去 getApplicationEventMulticaster().addApplicationListener(listener); } //获取bean定义中的监听器对象 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); //把监听器的名称注册到我们的事件多播器上 for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } //在这里获取我们的早期事件 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { //通过多播器进行播发早期事件 for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
如何发布事件,通过事件多播器方法:multicastEvent(ApplicationEvent event),进入方法
@Override public void multicastEvent(ApplicationEvent event) { multicastEvent(event, resolveDefaultEventType(event)); }
multicastEvent(event, resolveDefaultEventType(event))方法:
@Override public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) { ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event)); //从事件多播器中获取出所有的监听器 for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) { //判断多播器中是否支持异步多播的 Executor executor = getTaskExecutor(); if (executor != null) { //异步播发事件 executor.execute(() -> invokeListener(listener, event)); } else {//同步播发 invokeListener(listener, event); } } }
invokeListener(listener, event)方法:
/** * Invoke the given listener with the given event. * @param listener the ApplicationListener to invoke * @param event the current event to propagate * @since 4.1 */ protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) { ErrorHandler errorHandler = getErrorHandler(); if (errorHandler != null) { try { doInvokeListener(listener, event); } catch (Throwable err) { errorHandler.handleError(err); } } else { doInvokeListener(listener, event); } }
doInvokeListener(ApplicationListener listener, ApplicationEvent event) 方法(Spring有一个特点涉及到以do开头的方法都是真正干活的):
第十一步:finishBeanFactoryInitialization(beanFactory)
实例化所有的非懒加载的单实例bean:详解见:Spring IoC源码解析之getBean
第十二步:finishRefresh()
最后刷新容器发布刷新事件(Spring cloud eureka也是从这里启动的):
protected void finishRefresh() { //初始化生命周期处理器 initLifecycleProcessor(); //调用生命周期处理器的onRefresh方法 getLifecycleProcessor().onRefresh(); //发布ContextRefreshedEvent事件 publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext(this); }
① 初始化生命周期处理器:initLifecycleProcessor()方法:
protected void initLifecycleProcessor() { //获取beanFactory工厂 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //判断容器中是否有lifecycleProcessor,有就直接从容器中拿 if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) { this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class); if (logger.isDebugEnabled()) { logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]"); } } //没有创建一个DefaultLifecycleProcessor,然后注册到容器中 else { DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor(); defaultProcessor.setBeanFactory(beanFactory); this.lifecycleProcessor = defaultProcessor; beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor); if (logger.isDebugEnabled()) { logger.debug("Unable to locate LifecycleProcessor with name '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "': using default [" + this.lifecycleProcessor + "]"); } } }
② 调用生命周期处理器的onRefresh方法:getLifecycleProcessor().onRefresh():org.springframework.context.support.DefaultLifecycleProcessor#onRefresh:
@Override public void onRefresh() { startBeans(true); this.running = true; }
startBeans(true)方法:org.springframework.context.support.DefaultLifecycleProcessor#startBeans:主要的功能是找到Spring容器的Lifecycle类型的Bean,然后调用start()去启动
private void startBeans(boolean autoStartupOnly) { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new HashMap<Integer, LifecycleGroup>(); for (Map.Entry<String, ? extends Lifecycle> entry : lifecycleBeans.entrySet()) { Lifecycle bean = entry.getValue(); if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) { int phase = getPhase(bean); LifecycleGroup group = phases.get(phase); if (group == null) { group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly); phases.put(phase, group); } group.add(entry.getKey(), bean); } } if (!phases.isEmpty()) { List<Integer> keys = new ArrayList<Integer>(phases.keySet()); Collections.sort(keys); for (Integer key : keys) { phases.get(key).start(); } } }
start()方法:
doStart(this.lifecycleBeans, member.name, this.autoStartupOnly)方法:
private void doStart(Map<String, ? extends Lifecycle> lifecycleBeans, String beanName, boolean autoStartupOnly) { Lifecycle bean = lifecycleBeans.remove(beanName); if (bean != null && bean != this) { String[] dependenciesForBean = getBeanFactory().getDependenciesForBean(beanName); for (String dependency : dependenciesForBean) { doStart(lifecycleBeans, dependency, autoStartupOnly); } //bean不在运行中并且(autoStartupOnly=false 或者 不是SmartLifecycle类型 或者 isAutoStartup() = true) if (!bean.isRunning() && (!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) { if (logger.isDebugEnabled()) { logger.debug("Starting bean '" + beanName + "' of type [" + bean.getClass().getName() + "]"); } try { //调用生命周期Lifecycle Bean的start()方法 bean.start(); } catch (Throwable ex) { throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex); } if (logger.isDebugEnabled()) { logger.debug("Successfully started bean '" + beanName + "'"); } } } }
③ 发布ContextRefreshedEvent事件:主要就是调用前面第八步创建的事件多播器的发布事件方法getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType):
protected void publishEvent(Object event, ResolvableType eventType) { Assert.notNull(event, "Event must not be null"); if (logger.isTraceEnabled()) { logger.trace("Publishing event in " + getDisplayName() + ": " + event); } // Decorate event as an ApplicationEvent if necessary ApplicationEvent applicationEvent; if (event instanceof ApplicationEvent) { applicationEvent = (ApplicationEvent) event; } else { applicationEvent = new PayloadApplicationEvent<Object>(this, event); if (eventType == null) { eventType = ((PayloadApplicationEvent) applicationEvent).getResolvableType(); } } // Multicast right now if possible - or lazily once the multicaster is initialized if (this.earlyApplicationEvents != null) { this.earlyApplicationEvents.add(applicationEvent); } else { getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); } // Publish event via parent context as well... if (this.parent != null) { if (this.parent instanceof AbstractApplicationContext) { ((AbstractApplicationContext) this.parent).publishEvent(event, eventType); } else { this.parent.publishEvent(event); } } }
总结:从Spring IoC的源码解析过程中,我们更加深入的了解容器的初始化,Bean的后置处理器,国际化,事件多播器发布事件,Bean的创建,属性的赋值,三级缓存解决循环依赖问题,Lifecycle的作用,Spring场景应用:Spring系列(二):Spring IoC应用,Spring系列完整代码在码云:spring系列
原文链接:https://www.cnblogs.com/toby-xu/p/11324776.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- Spring系列.ApplicationContext接口 2020-06-11
- springboot2配置JavaMelody与springMVC配置JavaMelody 2020-06-11
- 给你一份超详细 Spring Boot 知识清单 2020-06-11
- SpringBoot 2.3 整合最新版 ShardingJdbc + Druid + MyBatis 2020-06-11
- 掌握SpringBoot-2.3的容器探针:实战篇 2020-06-11
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash