说明
一直有阅读Spring的念头,现在觉得不读源码并不代表自己熟悉一门框架。而且spring是平时最常用的框架。
类图
类图显示2条线,一种是xml配置方式,一种显示注解配置方式。现在我们都用注解方式比较多
main
@Test public void lqTEST() {
//<1> ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( new String[] {LQCONTEXT}, getClass()); assertTrue(ctx.getBean(Student.class).getClasses()!=null); ctx.close(); }
xml配置
<beans> <bean name="student" class="org.springframework.lq.Student"></bean> </beans>
ClassPathXmlApplicationContext
<1>
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz) throws BeansException { //<2> this(paths, clazz, null); }
<2>
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, @Nullable ApplicationContext parent) throws BeansException { super(parent); Assert.notNull(paths, "Path array must not be null"); Assert.notNull(clazz, "Class argument must not be null"); //要解析的配置文件 this.configResources = new Resource[paths.length]; for (int i = 0; i < paths.length; i++) { //封装成ClassPathResource this.configResources[i] = new ClassPathResource(paths[i], clazz); } //<3>开始执行容器初始化 refresh(); }
AbstractApplicationContext
<3>
org.springframework.context.support.AbstractApplicationContext#refresh
@Override public void refresh() throws BeansException, IllegalStateException { /* *加锁 防止在初始化过程中,继续调用初始化和 销毁的方法 */ synchronized (this.startupShutdownMonitor) { //初始化容器的准备工作 // <4>将 active 属性设置为 true,closed 属性设置为 false,它们都是 AtomicBoolean 类型 prepareRefresh(); //将会初始化 BeanFactory、加载 Bean、注册 Bean 等等。只是将需要初始化的bean通过BeanDefinition封装 //<5>BeanDefinition封装了如何初始化bean ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //<19>为beanFactory设置创建bean的ClassLoader 添加几个 BeanPostProcessor,手动注册几个特殊的 bean 供后续使用 prepareBeanFactory(beanFactory); try { /** *这里是提供给子类的扩展点,到这里的时候,所有的 Bean 都加载、注册完成了,但是都还没有初始化 *通过beanFactory我们可以获取并改变BeanDefinition 的属性改变将要创建bean的信息 * 钩子方法 目前空实现 */ postProcessBeanFactory(beanFactory); /** * 1.实例化并调用所有已注册的 BeanFactoryPostProcessor的实现类 * 这里是spring提供的扩展展点。我们可以通过实现BeanFactoryPostProcessor 在回调拿到beanFactory * 我们可以往里面注册BeanDefinition或者改变Definition的值 * 注册: *可以参考:org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition使用 *BeanDefinitionReaderUtils#registerBeanDefinition 注册 使用例子可参考:附录 * */ invokeBeanFactoryPostProcessors(beanFactory); /** * 初始化 BeanPostProcessor的实现类 注意这里并没有调用 只是先初始化这个接口的实现类到容器 * 1.实例化、依赖注入完毕,在调用显示的初始化之前完成一些定制的初始化任务 * 2.实例化、依赖注入、初始化完毕时执行 */ registerBeanPostProcessors(beanFactory); //初始化当前 ApplicationContext 的 MessageSource 国际化相关 initMessageSource(); /** * 初始化当前 ApplicationContext 的事件广播器 先在容器中找 如果没有则创建默认的 * ApplicationEventMulticaster 这个接口可以管理很多个ApplicationListener对象。并将事件发布给这些监听器
* 可参考附录用法 */ initApplicationEventMulticaster(); //扩展方法 具体的子类可以在这里初始化一些特殊的 Bean(在初始化 singleton beans 之前) onRefresh(); // 注册事件监听器,监听器需要实现 ApplicationListener 接口 <35> registerListeners(); /** * 核心方法 * <20>初始化所有的 singleton bean BeanDefinition isLazyInit为 lazy-init 的除外 */ finishBeanFactoryInitialization(beanFactory); /** * 完成刷新Context,主要调用org.springframework.context.LifecycleProcessor接口onRefresh方法,发布事件ContextRefreshedEvent事件 */ finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // 销毁已经初始化的 singleton 的 Beans,以免有些 bean 会一直占用资源 destroyBeans(); // 将active 设置为false 表示此容器不可用 cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { //重置Spring核心中的常见内核缓存,因为我们可能不再需要单例bean的元数据了 resetCommonCaches(); } } }
<4>
org.springframework.context.support.AbstractApplicationContext#prepareRefresh
protected void prepareRefresh() { // Switch to active. this.startupDate = System.currentTimeMillis(); //未关闭 this.closed.set(false); //已激活 this.active.set(true); ........省略部分 }
<5>
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //<6>销毁初始化过的BeanFactory 创建新的BeanFactory 加载Bean定义和注册Bean 模板方法由子类实现 refreshBeanFactory(); //获得BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); } return beanFactory; }
<19>
org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { /** *设置 BeanFactory 的类加载器,我们知道 BeanFactory 需要加载类,也就需要类加载器, *这里设置为加载当前 ApplicationContext 类的类加载器 */ beanFactory.setBeanClassLoader(getClassLoader()); /** *设置beanFactory的表达式语言处理器,Spring3增加了表达式语言的支持, *默认可以使用#{bean.xxx}的形式来调用相关属性值 */ beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); /** * 为beanFactory增加了一个默认的propertyEditor,这个主要是对bean的属性等设置管理的一个工具 */ beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); /** * 添加一个 BeanPostProcessor,这个 processor 比较简单: *实现了 Aware 接口的 beans 在初始化的时候,这个 processor 负责回调实现注入 *点进去下一下源码就清楚了 *org.springframework.context.support.ApplicationContextAwareProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String) */ beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //如果某个 bean 依赖于以下几个接口的实现类,在自动装配的时候忽略它们, //比如 注入 @autowired EnvironmentAware ev; beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); /** * Spring自动装配的时候如果一个接口有多个实现类,并且都已经放到IOC中去了, * 那么自动装配的时候就会出异常,因为spring不知道把哪个实现类注入进去, * 所以再这里指定注入哪个对象 */ beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); /** * 1、在Bean初始化完成之后:如果Bean是单例的则并且bean instanceof ApplicationListener。加入到this.applicationListeners中。 * 2、在Bean销毁之前搞事情: 如果Bean是一个ApplicationListener,则会从ApplicationEventMulticaster(事件广播器)中提前删除了
* 可以参考附录 ApplicationListener的用法 */ beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); /** * 如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ。 * 则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,从而实现类加载期织入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())); } /** * 以下是当我们配有配置 spring注册一个默认的 * 比如:如果容器中没有environment 则注册一个默认的 */ if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } //注册系统配置systemProperties组件Bean if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } //注册系统环境systemEnvironment组件Bean if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
<20>
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { /// 为上下文初始化类型转换器 首先,初始化名字为 conversionService的bean 需要实现ConversionService 的 Bean spring的类型转换器(非常实用) //可以参考此org.springframework.context.support.ConversionServiceFactoryBean用法 可参考附录用法 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { //通过getBean初始化并设置到beanFactory beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } // 检查上下文中是否存在类型转换器 如没有则创建一个默认的 处理@Value注解 if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } // 先初始化 LoadTimeWeaverAware 类型的 Bean 以便尽早注册它们的转换器。AspectJ 相关的内容 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // // 禁止使用临时类加载器进行类型匹配 beanFactory.setTempClassLoader(null); /** * 设置configurationFrozen为true * 因为到这一步的时候,Spring 已经开始预初始化 singleton beans 了,这个时候肯定不希望这个时候还出现 bean 定义解析、加载、注册。所以打上标识 */ beanFactory.freezeConfiguration(); //<21>开始初始化 beanFactory.preInstantiateSingletons(); }
<35>
org.springframework.context.support.AbstractApplicationContext#registerListeners
protected void registerListeners() { //从容器获得所有ApplicationListener 将容器局部变量的Linstenner设置到容器 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); } // 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) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
AbstractRefreshableApplicationContext
<6>
这里我们可以看到 虽然容器实现了BeanFactory 但是是组合关系 而非继承关系 BeanFactory相关都委托给了内部属性BeanFacotry 自己没有相关实现
org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory
protected final void refreshBeanFactory() throws BeansException { /** * 判断是否Application是否加载过beanFactory * 如果 ApplicationContext 中已经加载过 BeanFactory 了,销毁所有 Bean,关闭 BeanFactory *注意,应用中 BeanFactory 本来就是可以多个的,这里可不是说应用全局是否有 BeanFactory,而是当前 * ApplicationContext 是否有 BeanFactory 主要看容器实现 */ if (hasBeanFactory()) { //销毁BeanFactory destroyBeans(); closeBeanFactory(); } try { /** * 创建一个DefaultListableBeanFactory 如果当前容器有父容器则将父容器的BeanFactory设置为当前BeanFactory的父级 * 如果父级是ConfigurableApplicationContext 则获取父级的BeanFactory * 如果非ConfigurableApplicationContext类型 则直接使用父容器 因为父容器也实现了BeanFactory */ DefaultListableBeanFactory beanFactory = createBeanFactory(); //序列化的SerializationId beanFactory.setSerializationId(getId()); // 设置 BeanFactory 的两个配置属性:是否允许 Bean 覆盖、是否允许循环引用 customizeBeanFactory(beanFactory); /** * 加载 BeanDefinition 到 BeanFactory 中 模板方法子类实现 * 比如classPath则扫描xml 解析并生成 * 如果是注解 则扫描注解 反射解析生成 * <7>模板方法 由子类自定义实现 */ loadBeanDefinitions(beanFactory); this.beanFactory = beanFactory; } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
AbstractXmlApplicationContext
<7>
解析xml的方式是委托给XmlBeanDefinitionReader
org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { /// 将BeanFactory设置到reader BeanFactory 实例化一个 XmlBeanDefinitionReader 将解析xml的操作委托给它处理 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); //要扫描的资源信息 beanDefinitionReader.setResourceLoader(this); /** * entityResolver的作用是项目本身就可以提供一个如何寻找DTD声明的方法,即由程序来实现寻找DTD声明的过程, * 比如我们将DTD文件放到项目中某处,在实现时直接将此文档读取并返回给SAX即可。这样就避免了通过网络来寻找相应的声明。 */ beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); /** * //当Bean 读取器读取Bean 定义的Xml 资源文件时,启用Xml 的校验机制 */ initBeanDefinitionReader(beanDefinitionReader); /** * <8>加载beanDefinition */ loadBeanDefinitions(beanDefinitionReader); }
<8>
org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { //获得要价值的xmlResource Resource[] configResources = getConfigResources(); if (configResources != null) { reader.loadBeanDefinitions(configResources); } //子类重写 xml配置的路径, String[] configLocations = getConfigLocations(); if (configLocations != null) { //<9>进行加载 reader.loadBeanDefinitions(configLocations); } }
AbstractBeanDefinitionReader
<9>
@Override public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException { Assert.notNull(locations, "Location array must not be null"); int counter = 0; //资源文件可以配置多个 所以循环加载 for (String location : locations) { //<10>执行xml加载 counter += loadBeanDefinitions(location); } return counter; }
<10>
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException { //这里的ResoureceLoader是真实的beanFacotry容器实现了接口 ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader == null) { throw new BeanDefinitionStoreException( "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available"); } //判断是否实现了Resolver接口如果实现了 则传入路径 返回Resource // 这里是个扩展点,我们可以通过容器的ResourcePatternResolver 返回加载配置的地址 if (resourceLoader instanceof ResourcePatternResolver) { // Resource pattern matching available. try { //如果 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); //加载 int loadCount = loadBeanDefinitions(resources); if (actualResources != null) { for (Resource resource : resources) { actualResources.add(resource); } } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]"); } return loadCount; } catch (IOException ex) { throw new BeanDefinitionStoreException( "Could not resolve bean definition resource pattern [" + location + "]", ex); } } else { //从BeanFactory里面根据location获取Resource Resource resource = resourceLoader.getResource(location); //<11>模板方法 子类实现 int loadCount = loadBeanDefinitions(resource); if (actualResources != null) { actualResources.add(resource); } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]"); } return loadCount; } }
XmlBeanDefinitionReader
<11>
org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions(org.springframework.core.io.support.EncodedResource)
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); } // 用一个 ThreadLocal 来存放配置文件资源 Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get(); if (currentResources == null) { currentResources = new HashSet<>(4); this.resourcesCurrentlyBeingLoaded.set(currentResources); } //表示重复加载了 if (!currentResources.add(encodedResource)) { throw new BeanDefinitionStoreException( "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); } try { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { //通知 SAX 解析器使用何种编码;在涉及国际化或使用多字节字符集的 XML 应用程序中 inputSource.setEncoding(encodedResource.getEncoding()); } //<12>进行加载 return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally { inputStream.close(); } } catch (IOException ex) { throw new BeanDefinitionStoreException( "IOException parsing XML document from " + encodedResource.getResource(), ex); } finally { currentResources.remove(encodedResource); if (currentResources.isEmpty()) { this.resourcesCurrentlyBeingLoaded.remove(); } } }
<12>
org.springframework.beans.factory.xml.XmlBeanDefinitionReader#doLoadBeanDefinitions
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException { try { //将XML转换为Document对象 Document doc = doLoadDocument(inputSource, resource); //<13>解析doc 并封装成Definition return registerBeanDefinitions(doc, resource); } catch (BeanDefinitionStoreException ex) { throw ex; } catch (SAXParseException ex) { throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex); } catch (SAXException ex) { throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", ex); } catch (ParserConfigurationException ex) { throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, ex); } catch (IOException ex) { throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, ex); } catch (Throwable ex) { throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, ex); } }
<13>
org.springframework.beans.factory.xml.XmlBeanDefinitionReader#registerBeanDefinitions
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { //获得的的读取器 BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); int countBefore = getRegistry().getBeanDefinitionCount(); //<14>解析Document 并注册到Bean Facotry documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); return getRegistry().getBeanDefinitionCount() - countBefore; }
DefaultBeanDefinitionDocumentReader
<14>
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions
protected void doRegisterBeanDefinitions(Element root) { // 我们看名字就知道,BeanDefinitionParserDelegate 必定是一个重要的类,它负责解析 Bean 定义, // 这里为什么要定义一个 parent? 看到后面就知道了,是递归问题, // 因为 <beans /> 内部是可以定义 <beans /> 的,所以这个方法的 root 其实不一定就是 xml 的根节点,也可以是嵌套在里面的 <beans /> 节点, // 从源码分析的角度,我们当做根节点就好了 BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createDelegate(getReaderContext(), root, parent); if (this.delegate.isDefaultNamespace(root)) { String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE); //// 这块说的是根节点 <beans ... profile="dev" /> 中的 profile 是否是当前环境需要的, if (StringUtils.hasText(profileSpec)) { String[] specifiedProfiles = StringUtils.tokenizeToStringArray( profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); //// 如果当前环境配置的 profile 不包含此 profile,那就直接 return 了,不对此 <beans /> 解析 if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) { if (logger.isInfoEnabled()) { logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + getReaderContext().getResource()); } return; } } } //提供给子类的扩展方法 preProcessXml(root); //<15>从头root节点开始解析 parseBeanDefinitions(root, this.delegate); //提供给子类的扩展方法 postProcessXml(root); this.delegate = parent; }
<15>
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseBeanDefinitions
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { //是否定义namespace http://www.springframework.org/schema/beans if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { /** * <16></>parseDefaultElement(ele, delegate) 代表解析的节点是 <import />、<alias />、<bean />、<beans /> 这几个。 */ parseDefaultElement(ele, delegate); } else { /** * 解析扩展标签 如 <mvc />、<task />、<context />、<aop />等。通过schema 可以参考dubbo的实现 * 如 MvcNamespaceHandler、TaskNamespaceHandler、ContextNamespaceHandler、AopNamespaceHandler 等 */ delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }
<16>
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseDefaultElement
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { // 处理 <import /> 标签 importBeanDefinitionResource(ele); } else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { // 处理 <alias /> 标签定义 // <alias name="fromName" alias="toName"/> processAliasRegistration(ele); } else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { // <17>处理 <bean /> 标签定义,这也算是我们的重点吧 processBeanDefinition(ele, delegate); } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { // 如果碰到的是嵌套的 <beans /> 标签,需要递归 doRegisterBeanDefinitions(ele); } }
<17>
org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { // 将 <bean /> 节点中的信息提取出来,然后封装到一个 BeanDefinitionHolder 中,细节往下看 BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { // 如果有自定义属性的话,进行相应的解析 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { // <18>我们把这步叫做 注册Bean BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } catch (BeanDefinitionStoreException ex) { getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // 注册完成后,发送事件 getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } }
<18>
org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition
public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); // 注册这个 Bean registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // 如果还有别名的话,也要根据别名全部注册一遍,不然根据别名就会找不到 Bean 了 String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String alias : aliases) { // alias -> beanName 保存它们的别名信息,这个很简单,用一个 map 保存一下就可以了, // 获取的时候,会先将 alias 转换为 beanName,然后再查找 registry.registerAlias(beanName, alias); } } }
到这里 如何初始化对象就交给BeanDefinition封装起来了。但是还没有初始化
BeanDefinition代码太长就不贴了 可以去看一下BeanDefinition的定义
DefaultListableBeanFactory
<21>
org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
public void preInstantiateSingletons() throws BeansException { if (logger.isDebugEnabled()) { logger.debug("Pre-instantiating singletons in " + this); } // this.beanDefinitionNames 保存了所有的 beanNames List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); //触发所有的非懒加载的 singleton beans 的初始化操作 for (String beanName : beanNames) { /** * / 合并父 Bean 中的配置,如: <bean id="" class="" parent="" /> 中的 parent * 具体看 bean parent用法 */ RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 非抽象、非懒加载的 singletons。如果配置了 'abstract = true',那是不需要初始化的 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { //是否是factoryBean 可参考附录 if (isFactoryBean(beanName)) { //如果是FactoryBean则初始化 并在beanName前面拼上& Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; //判断factory是否是SmartFactoryBean实现 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 { //<22>对于普通的 Bean,只要调用 getBean(beanName) 这个方法就可以进行初始化了 getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... 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(); } } } }
AbstractBeanFactory
<22>
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)
@Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { // 获取一个 “正统的” beanName,处理两种情况,一个是前面说的 FactoryBean(前面带 ‘&’),去掉& // 一个传入的是别名问题,因为这个方法是 getBean,获取 Bean 用的,你要是传一个别名进来,是完全可以的 String beanName = transformedBeanName(name); Object bean; /** * 根据beanName尝试从singletonObjects获取Bean * 获取不到则再尝试从earlySingletonObjects,singletonFactories 从获取Bean * 这段代码和解决循环依赖有关 */ Object sharedInstance = getSingleton(beanName); //// 第一次进入sharedInstance肯定为null if (sharedInstance != null && args == null) { if (logger.isDebugEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference"); } else { logger.debug("Returning cached instance of singleton bean '" + beanName + "'"); } } // 下面这个方法:如果是普通 Bean 的话,直接返回 sharedInstance, // 如果是 FactoryBean 的话,调用getObject返回它创建的那个实例对象 bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { //判断是否循环依赖 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } //获取父BeanFactory,一般情况下,父BeanFactory为null,如果存在父BeanFactory,就先去父级容器去查找 BeanFactory parentBeanFactory = getParentBeanFactory(); //// 如果当前容器不存在这个 BeanDefinition,试试父容器中有没有 if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { //调用父容器的doGetBean尝试获取 String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else if (args != null) { return (T) parentBeanFactory.getBean(nameToLookup, args); } else { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } } // 创建的Bean是否需要进行类型验证,一般情况下都不需要 if (!typeCheckOnly) { //// 标记 bean 已经被创建 markBeanAsCreated(beanName); } try { //// 获取其父类Bean定义,子类合并父类公共属性 RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn != null) { for (String dep : dependsOn) { // 检查是不是有循环依赖, if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } // 如果当前Bean依赖其他Bean,把被依赖Bean注册给当前Bean registerDependentBean(dep, beanName); try { //// 先去创建所依赖的Bean getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // 如果是 singleton scope 的,创建 singleton 的实例 if (mbd.isSingleton()) { //创建单例bean sharedInstance = getSingleton(beanName, () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; } }); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } // 创建prototype Bean,每次都会创建一个新的对象 else if (mbd.isPrototype()) { // It's a prototype -> create a new instance. Object prototypeInstance = null; try { //// 回调beforePrototypeCreation方法,注册当前创建的原型对象 beforePrototypeCreation(beanName); //// 回调 afterPrototypeCreation 方法,告诉容器该Bean的原型对象不再创建 prototypeInstance = createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd); } else { //如果既不是单例Bean,也不是prototype,则获取其Scope 委托给相应的Scope实现类创建 String scopeName = mbd.getScope(); if (!StringUtils.hasLength(scopeName)) { throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'"); } Scope scope = this.scopes.get(scopeName); if (scope == null) { throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'"); } try { Object scopedInstance = scope.get(beanName, () -> { beforePrototypeCreation(beanName); try { //创建bean 传入beanName,RootBeanDefinition 抽象方法 子类实现 //<23>args 数组代表创建实例需要的参数,不就是给构造方法用的参数,或者是工厂 Bean 的参数嘛,不过要注意,在我们的初始化阶段,args 是 null。 return createBean(beanName, mbd, args); } finally { afterPrototypeCreation(beanName); } }); bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd); } catch (IllegalStateException ex) { throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", ex); } } } catch (BeansException ex) { cleanupAfterBeanCreationFailure(beanName); throw ex; } } // 最后如果设置了类型requiredType,检查一下类型对不对,不对的话就抛异常,对的话就返回了 if (requiredType != null && !requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }
AbstractAutowireCapableBeanFactory
<23>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { if (logger.isDebugEnabled()) { logger.debug("Creating instance of bean '" + beanName + "'"); } RootBeanDefinition mbdToUse = mbd; // // 获得beanDefinition的class Class<?> resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { /** *准备方法覆写,这里又涉及到一个概念:MethodOverrides,它来自于 bean 定义中的<lookup -method / > * 和 <replaced-method /> 可参考 附录 */ mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try { // 让 InstantiationAwareBeanPostProcessor 在这一步有机会替代对象。 此接口是BeanPostProcessor的子接口 Object bean = resolveBeforeInstantiation(beanName, mbdToUse); //如果通过此扩展点创建了对象 则直接返回对象 不会执行下面createBean if (bean != null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { //<24>重头戏,创建 bean Object beanInstance = doCreateBean(beanName, mbdToUse, args); if (logger.isDebugEnabled()) { logger.debug("Finished creating instance of bean '" + beanName + "'"); } return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { // A previously detected exception with proper bean creation context already, // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry. throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } }
<24>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
protected Object doCreatexBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { // Instantiate the bean. BeanWrapper instanceWrapper = null; // //如果RootBeanDefinition是单例的,则移除未完成的FactoryBean实例的缓存 if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //<25>这里实例化 Bean 通过BeanWrapper包装 instanceWrapper = createBeanInstance(beanName, mbd, args); } // 这个就是 Bean 里面的 我们定义的类 的实例,很多地方我直接描述成 "bean 实例" Object bean = instanceWrapper.getWrappedInstance(); //获取bean的Class Class<?> beanType = instanceWrapper.getWrappedClass(); if (beanType != NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { //bean 的生命周期之一。如果实现了MergedBeanDefinitionPostProcessor会在这里调用postProcessMergedBeanDefinition方法 //代表性的实现就是org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor //找到打上@Autowired @Value注解的元数据信息 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } //// 下面这块代码是为了解决循环依赖的问题 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"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); } // Initialize the bean instance. Object exposedObject = bean; try { /** * 负责装配bean的属性 静态注入 *<27> @Autowrit @Value动态注入 InstantiationAwareBeanPostProcessor * */ populateBean(beanName, mbd, instanceWrapper); //<30>bean初始化完成后的各种回调 exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } } // Register bean as disposable. try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
<25>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { //beanDefinition解析bean的class Class<?> beanClass = resolveBeanClass(mbd, beanName); //校验一下是否有访问权限 if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); } // 通过beanDefinition中的supplier实例化这个bean Supplier<?> instanceSupplier = mbd.getInstanceSupplier(); if (instanceSupplier != null) { return obtainFromSupplier(instanceSupplier, beanName); } // 通过FactoryMethod实例化这个bean if (mbd.getFactoryMethodName() != null) { return instantiateUsingFactoryMethod(beanName, mbd, args); } // 下面这段代码都是在通过构造函数实例化这个Bean,分两种情况,一种是通过默认的无参构造,一种 有参数的构造方法 //是否解析过 boolean resolved = false; //false无参 true有参 boolean autowireNecessary = false; if (args == null) { synchronized (mbd.constructorArgumentLock) { if (mbd.resolvedConstructorOrFactoryMethod != null) { resolved = true; autowireNecessary = mbd.constructorArgumentsResolved; } } } //如果解析过 判断是根据有参还是无参构造方式实例化对象 if (resolved) { if (autowireNecessary) { //有参构造函数 return autowireConstructor(beanName, mbd, null, null); } else { //无参构造函数 return instantiateBean(beanName, mbd); } } //未解析过 // Candidate constructors for autowiring? Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR || mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) { //有参构造函数 return autowireConstructor(beanName, mbd, ctors, args); } // <26>无参构造函数 return instantiateBean(beanName, mbd); }
<26>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) { try { Object beanInstance; if (System.getSecurityManager() != null) { beanInstance = AccessController.doPrivileged( (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this), getAccessControlContext()); } else { //创建bean beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this); } //通过BeanWrapper包装返回 BeanWrapper bw = new BeanWrapperImpl(beanInstance); initBeanWrapper(bw); return bw; } catch (Throwable ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex); } }
<27>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) { if (bw == null) { if (mbd.hasPropertyValues()) { //如果有BeanWrapper 但是有又有属性值则抛异常 throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance"); } else { // Skip property population phase for null instance. return; } } // 到这步的时候,bean 实例化完成(通过工厂方法或构造方法),但是还没开始属性设值, // InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改, //比如dubbo 服务消费者 通过代理实现@Refrence注入属性值 if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理 if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } //静态注入 里面默认会存储注入关系 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); int resolvedAutowireMode = mbd.getResolvedAutowireMode(); //=============================autowireMode注入方式 不用打任何注解 自动注入 详细可搜索用法========================== if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); //<28> 根据属性名称在容器查找bean if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs); } //<29>根据属性类型在容器查找bean if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; } //容器是否有InstantiationAwareBeanPostProcessor boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors(); boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); if (hasInstAwareBpps || needsDepCheck) { if (pvs == null) { pvs = mbd.getPropertyValues(); } PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); if (hasInstAwareBpps) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { // 这里有个非常有用的 BeanPostProcessor 进到这里: AutowiredAnnotationBeanPostProcessor //// 对采用 @Autowired、@Value 注解的依赖进行设值 InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); if (pvs == null) { return; } } } } if (needsDepCheck) { checkDependencies(beanName, mbd, filteredPds, pvs); } } if (pvs != null) { // 设置 bean 实例的属性值 applyPropertyValues(beanName, mbd, bw, pvs); } }
<28>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByName
protected void autowireByName( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 获取可set的属性,且这个属性不是简单的属性,比如基本类型、包装类这些 String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { //// 是否有这个bean if (containsBean(propertyName)) { // 有的话获取 Object bean = getBean(propertyName); // 添加到pvs pvs.add(propertyName, bean); // // 注册依赖关系 registerDependentBean(propertyName, beanName); if (logger.isDebugEnabled()) { logger.debug("Added autowiring by name from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + propertyName + "'"); } } else { if (logger.isTraceEnabled()) { logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName + "' by name: no matching bean found"); } } } }
<29>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByType
protected void autowireByType( String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) { // 类型转换器获取 TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } //==================== 获取可set的属性,且这个属性不是简单的属性,比如基本类型、包装类这些=================== Set<String> autowiredBeanNames = new LinkedHashSet<>(4); String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw); for (String propertyName : propertyNames) { try { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); // 如果是Object,就不管了 if (Object.class != pd.getPropertyType()) { // 获取写参数 MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd); // Do not allow eager init for type matching in case of a prioritized post-processor. boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered); DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager); Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter); if (autowiredArgument != null) { pvs.add(propertyName, autowiredArgument); } for (String autowiredBeanName : autowiredBeanNames) { // 注册依赖 registerDependentBean(autowiredBeanName, beanName); if (logger.isDebugEnabled()) { logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" + propertyName + "' to bean named '" + autowiredBeanName + "'"); } } autowiredBeanNames.clear(); } } catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex); } } }
<30>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else { //<31> 如果 bean 实现了 BeanNameAware、BeanClassLoaderAware 或 BeanFactoryAware 接口,回调 invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || !mbd.isSynthetic()) { //<32> BeanPostProcessor 的 postProcessBeforeInitialization 回调 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); } try { ////<处理 bean 中定义的 init-method, // <33> // 或者如果 bean 实现了 InitializingBean 接口,调用 afterPropertiesSet() 方法 invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd != null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || !mbd.isSynthetic()) { //<34>BeanPostProcessor 的 postProcessAfterInitialization 回调 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } return wrappedBean; }
<31>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods
private void invokeAwareMethods(String beanName, Object bean) { /** * 判断是否实现了Aware接口 * 依次判断是否实现了 BeanNameAware BeanClassLoaderAware BeanFactoryAware并调用对应的方法 */ if (bean instanceof Aware) { if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName); } if (bean instanceof BeanClassLoaderAware) { ClassLoader bcl = getBeanClassLoader(); if (bcl != null) { ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl); } } if (bean instanceof BeanFactoryAware) { ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this); } } }
<32>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }
<33>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean); //判断是否实现了InitializingBean接口和是否实现了initMethod方法 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((PrivilegedExceptionAction<Object>) () -> { ((InitializingBean) bean).afterPropertiesSet(); return null; }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { //执行调用 ((InitializingBean) bean).afterPropertiesSet(); } } //如果配置了initMethod 就执行initMethod方法 这里只是取到了方法名,显然是要通过反射调用了 if (mbd != null && bean.getClass() != NullBean.class) { String initMethodName = mbd.getInitMethodName(); if (StringUtils.hasLength(initMethodName) && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); } } }
<34>
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization
@Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; //获得实现了BeanPostProcessor的累的对象遍历调用postProcessAfterInitialization for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName); if (current == null) { return result; } result = current; } return result; }