前面两篇文章分析了super(this)和setConfigLocations(configLocations)的源代码,本文来分析下refresh的源码,***[Spring加载流程源码分析01【super】](https://blog.csdn.net/qq_38526573/article/details/87870315)Spring加载流程源码分析02【setConfigLocations】***先来看下ClassPathXmlApplicationContext类的初始化过程:public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } }
refresh方法的具体实现是在AbstractApplicationContext类中如下:@Override public void refresh() throws BeansException, IllegalStateException { //startupShutdownMonitor对象在spring环境刷新和销毁的时候都会用到,确保刷新和销毁不会同时执行 synchronized (this.startupShutdownMonitor) { // 准备工作,例如记录事件,设置标志,检查环境变量等,并有留给子类扩展的位置,用来将属性加入到applicationContext中 prepareRefresh(); // 创建beanFactory,这个对象作为applicationContext的成员变量,可以被applicationContext拿来用, // 并且解析资源(例如xml文件),取得bean的定义,放在beanFactory中 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 对beanFactory做一些设置,例如类加载器、SPEL解析器、指定bean的某些类型的成员变量对应某些对象. prepareBeanFactory(beanFactory); try { // 子类扩展用,可以设置bean的后置处理器(bean在实例化之后这些后置处理器会执行) postProcessBeanFactory(beanFactory); // 执行beanFactory后置处理器(有别于bean后置处理器处理bean实例,beanFactory后置处理器处理bean定义) invokeBeanFactoryPostProcessors(beanFactory); // 将所有的bean的后置处理器排好序,但不会马上用,bean实例化之后会用到 registerBeanPostProcessors(beanFactory); // 初始化国际化服务 initMessageSource(); // 创建事件广播器 initApplicationEventMulticaster(); // 空方法,留给子类自己实现的,在实例化bean之前做一些ApplicationContext相关的操作 onRefresh(); // 注册一部分特殊的事件监听器,剩下的只是准备好名字,留待bean实例化完成后再注册 registerListeners(); // 单例模式的bean的实例化、成员变量注入、初始化等工作都在此完成 finishBeanFactoryInitialization(beanFactory); // applicationContext刷新完成后的处理,例如生命周期监听器的回调,广播通知等 finishRefresh(); } catch (BeansException ex) { logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex); // 刷新失败后的处理,主要是将一些保存环境信息的集合做清理 destroyBeans(); // applicationContext是否已经激活的标志,设置为false cancelRefresh(ex); // Propagate exception to caller. throw ex; } } }
接下来一一介绍下
protected void prepareRefresh() { // 设置初始化开始的时间 this.startupDate = System.currentTimeMillis(); // 设置context的关闭状态为false this.closed.set(false); // 设置context的活动状态是true this.active.set(true); if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); } // Initialize any placeholder property sources in the context environment // 留个子类自己实现的空方法 initPropertySources(); // 验证对应的key在环境变量中是否存在,如果不存在就抛异常 getEnvironment().validateRequiredProperties(); // earlyApplicationEvents存放早起的一些事件。 this.earlyApplicationEvents = new LinkedHashSet
initPropertySources() 留给子类实现的方法
protected void initPropertySources() { // For subclasses: do nothing by default. }
创建了一个BeanFactory对象/// / Tell the subclass to refresh the internal bean factory. / 子类实现 / @return the fresh BeanFactory instance / @see /#refreshBeanFactory() / @see /#getBeanFactory() // protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { // 子类(AbstractRefreshableApplicationContext)创建一个ConfigurableListableBeanFactory 对象 refreshBeanFactory(); // 获取refreshBeanFactory()实现类中创建的BeanFactory对象 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); } return beanFactory; }
该方法是子类实现的方法,在AbstractRefreshableApplicationContext类中该方法创建了ConfigurableListableBeanFactory 对象并且完成了,并赋值给了beanFactory@Override protected final void refreshBeanFactory() throws BeansException { // 如果BeanFactory存在就销毁 if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); // BeanFactory的初始化操作 beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); // 在次方法中完成了application.xml文件的解析 loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { // 创建的对象赋值给了成员变量beanFactory this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
进入loadBeanDefinitions(beanFactory)方法查看
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); // 进入该方法查看 loadBeanDefinitions(beanDefinitionReader); }
loadBeanDefinitions(beanDefinitionReader);
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException { String[] configLocations = getConfigLocations(); if (configLocations != null) { for (String configLocation : configLocations) { //继续进入 configLocation 是applicationContext.xml reader.loadBeanDefinitions(configLocation); } } }
进入跟踪
public int loadBeanDefinitions(String location, Set
继续跟踪
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { Assert.notNull(encodedResource, "EncodedResource must not be null"); if (logger.isInfoEnabled()) { logger.info("Loading XML bean definitions from " + encodedResource.getResource()); } Set
跟踪到如下代码
try { Document doc = doLoadDocument(inputSource, resource); return registerBeanDefinitions(doc, resource); }
上面是加载bean定义的关键代码:先制作Document对象,再调用registerBeanDefinitions方法,最终会将每个bean的定义放入DefaultListableBeanFactory的beanDefinitionMap中。
获取refreshBeanFactory()实现类中创建的BeanFactory对象@Override public final ConfigurableListableBeanFactory getBeanFactory() { synchronized (this.beanFactoryMonitor) { if (this.beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return this.beanFactory; } }
BeanFactory的预准备工作protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // 1)、设置BeanFactory的类加载器 beanFactory.setBeanClassLoader(getClassLoader()); // 1)、设置支持表达式解析器 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // 2)、添加部分BeanPostProcessor【ApplicationContextAwareProcessor】 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 3)、设置忽略的自动装配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx; // 这些接口的实现类不能通过类型来自动注入 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // 4)、注册可以解析的自动装配;我们能直接在任何组件中自动注入: //BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext // 其他组件中可以通过下面方式直接注册使用 @autowired BeanFactory beanFactory // beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // 5)、添加BeanPostProcessor【ApplicationListenerDetector】后置处理器,在bean初始化前后的一些工作 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // 6)、添加编译时的AspectJ; if (beanFactory.containsBean(LOADTIMEWEAVERBEANNAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } // 7)、给BeanFactory中注册一些能用的组件; if (!beanFactory.containsLocalBean(ENVIRONMENTBEANNAME)) { // 环境信息ConfigurableEnvironment beanFactory.registerSingleton(ENVIRONMENTBEANNAME, getEnvironment()); } //系统属性,systemProperties【Map
prepareBeanFactory方法就是为beanFactory做一些设置工作,传入一些后面会用到的参数和工具类,再在spring容器中创建一些bean;
postProcessBeanFactory方法是留给子类扩展的,可以在bean实例初始化之前注册后置处理器(类似prepareBeanFactory方法中的beanFactory.addBeanPostProcessor),以子类AbstractRefreshableWebApplicationContext为例,其postProcessBeanFactory方法protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); beanFactory.ignoreDependencyInterface(ServletConfigAware.class); WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig); }
除了WebApplicationContextUtils类的工作之外,其余的都是和prepareBeanFactory方法中类似的处理
nvokeBeanFactoryPostProcessors方法用来执行BeanFactory实例的后置处理器BeanFactoryPostProcessor的postProcessBeanFactory方法,这个后置处理器除了原生的,我们也可以自己扩展,用来对Bean的定义做一些修改,由于此时bean还没有实例化,所以不要在自己扩展的BeanFactoryPostProcessor中调用那些会触发bean实例化的方法(例如BeanFactory的getBeanNamesForType方法),源码的文档中有相关说明,不要触发bean的实例化,如果要处理bean实例请在BeanPostProcessor中进行;protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOADTIMEWEAVERBEANNAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
registerBeanPostProcessors方法的代码略多,就不在此贴出来了,简单的说,就是找出所有的bean的后置处理器(注意,是bean的后置处理器,不是beanFactory的后置处理器,bean后置处理器处理的是bean实例,beanfactory后置处理器处理的是bean的定义),然后将这些bean的后置处理器分为三类:
registerBeanPostProcessors方法执行完毕后,beanFactory中已经保存了有序的bean后置处理器,在bean实例化之后,会依次使用这些后置处理器对bean实例来做对应的处理;
initMessageSource方法用来准备国际化资源相关的,将实现了MessageSource接口的bean存放在ApplicationContext的成员变量中,先看是否有配置,如果有就实例化,否则就创建一个DelegatingMessageSource实例的bean
spring中有事件、事件广播器、事件监听器等组成事件体系,在initApplicationEventMulticaster方法中对事件广播器做初始化,如果找不到此bean的配置,就创建一个SimpleApplicationEventMulticaster实例作为事件广播器的bean,并且保存为applicationContext的成员变量applicationEventMulticaster/// / Initialize the ApplicationEventMulticaster. / Uses SimpleApplicationEventMulticaster if none defined in the context. / @see org.springframework.context.event.SimpleApplicationEventMulticaster // protected void initApplicationEventMulticaster() { //获取BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 判断是否存在 if (beanFactory.containsLocalBean(APPLICATIONEVENTMULTICASTERBEANNAME)) { // 从容器中获取ApplicationEventMulticaster对象 this.applicationEventMulticaster = beanFactory.getBean(APPLICATIONEVENTMULTICASTERBEANNAME, ApplicationEventMulticaster.class); if (logger.isDebugEnabled()) { logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // 初始一个SimpleApplicationEventMulticaster对象 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); // 创建的对象注册到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是个空方法,留给子类自己实现的,在实例化bean之前做一些ApplicationContext相关的操作,以子类AbstractRefreshableWebApplicationContext为例,看看它的onRefresh方法/// / Initialize the theme capability. // @Override protected void onRefresh() { this.themeSource = UiApplicationContextUtils.initThemeSource(this); }
方法名为registerListeners,看名字像是将监听器注册在事件广播器中,但实际情况并非如此,只有一些特殊的监听器被注册了,那些在bean配置文件中实现了ApplicationListener接口的类还没有实例化,所以此处只是将其name保存在广播器中,将这些监听器注册在广播器的操作是在bean的后置处理器中完成的,那时候bean已经实例化完成了,我们看代码protected void registerListeners() { // 注册的都是特殊的事件监听器,而并非配置中的bean 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! // 根据接口类型找出所有监听器的名称 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { // 这里只是把监听器的名称保存在广播器中,并没有将这些监听器实例化!!! getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } }
finishBeanFactoryInitialization方法做了两件事:
preInstantiateSingletons方法
public void preInstantiateSingletons() throws BeansException { if (this.logger.isDebugEnabled()) { this.logger.debug("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. List
doGetBean
protected
doCreateBean方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { // bean的包装 BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { // 1)、【创建Bean实例】利用工厂方法或者对象的构造器创建出Bean实例; instanceWrapper = createBeanInstance(beanName, mbd, args); } final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); Class> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); mbd.resolvedTargetType = beanType; // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { //调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName); //判断是否为:MergedBeanDefinitionPostProcessor 类型的,如果是,调用方法 //MergedBeanDefinitionPostProcessor 后置处理器是在bean实例换之后调用的 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } //判断bean 是否为单实例的,如果是单实例的添加到缓存中 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isDebugEnabled()) { logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } //添加bean到缓存中 addSingletonFactory(beanName, new ObjectFactory
populateBean()创建bean后属性赋值
//populateBean():1204, AbstractAutowireCapableBeanFactory protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) { PropertyValues pvs = mbd.getPropertyValues(); if (bw == null) { if (!pvs.isEmpty()) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the // state of the bean before properties are set. This can be used, for example, // to support styles of field injection. boolean continueWithPropertyPopulation = true; //赋值之前: // 1)、拿到InstantiationAwareBeanPostProcessor后置处理器; 执行处理器的postProcessAfterInstantiation(); 方法// if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; //执行 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { continueWithPropertyPopulation = false; break; } } } } if (!continueWithPropertyPopulation) { return; } if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYNAME || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYTYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // autowire 按name注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYNAME) { autowireByName(beanName, mbd, bw, newPvs); } // autowire 按类型注入 if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIREBYTYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCYCHECKNONE); //2)、拿到InstantiationAwareBeanPostProcessor后置处理器; 执行 postProcessPropertyValues(); 获取到属性的值,此时还未赋值// if (hasInstAwareBpps || needsDepCheck) { PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } //=====赋值之前:=== //3)、应用Bean属性的值;为属性利用setter方法等进行赋值; applyPropertyValues(beanName, mbd, bw, pvs); }
Bean初始化 initializeBean
//初始化 protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged(new PrivilegedAction
执行bean的初始化方法init1)是否是InitializingBean接口的实现;执行接口规定的初始化;2)是否自定义初始化方法;通过注解的方式添加了initMethod方法的,
例如: @Bean(initMethod="init",destroyMethod="detory")//invokeInitMethods():1667, AbstractAutowireCapableBeanFactory protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable { //1)、是否是InitializingBean接口的实现;执行接口规定的初始化 ,执行afterPropertiesSet()这个方法; boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isDebugEnabled()) { logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } if (System.getSecurityManager() != null) { try { AccessController.doPrivileged(new PrivilegedExceptionAction
最后一个方法是finishRefresh,这是在bean的实例化、初始化等完成后的一些操作,例如生命周期变更的回调,发送applicationContext刷新完成的广播等,展开看看protected void finishRefresh() { // 检查是否已经配置了生命周期处理器,如果没有就new一个DefaultLifecycleProcessor initLifecycleProcessor(); // 找到所有实现了Lifecycle接口的bean,按照每个bean设置的生命周期阶段进行分组,再依次调用每个分组中每个bean的start方法,完成生命周期监听的通知 getLifecycleProcessor().onRefresh(); // 创建一条代表applicationContext刷新完成的事件,交给广播器去广播 publishEvent(new ContextRefreshedEvent(this)); // 如果配置了MBeanServer,就完成在MBeanServer上的注册 LiveBeansView.registerApplicationContext(this); }