Spring是通过IoC容器对Bean进行管理的,而Bean的初始化主要分为两个过程:Bean的注册和Bean实例化。Bean的注册主要是指Spring通过读取配置文件获取各个bean的声明信息,并且对这些信息进行注册的过程。Bean的实例化则指的是Spring通过Bean的注册信息对各个Bean进行实例化的过程。本文主要讲解Spring是如何注册Bean,并且为后续的Bean实例化做准备的。
Spring提供了BeanFactory对Bean进行获取,但Bean的注册和管理并不是在BeanFactory中进行的,而是在BeanDefinitionRegistry中进行的,这里BeanFactory只是提供了一个查阅的功能。如果把整个IoC容器比作一个图书馆的话,BeanFactory只是提供给学生查阅书籍的管理员,而BeanDefinitionRegistry则是注册所有图书信息的图书管理软件。Spring的Bean信息是注册在一个个BeanDefinitioin中的,其就相当于一本本的图书,在图书管理软件中是注册备案了的。如下是IoC容器对Bean注册进行管理的类结构图:

1. bean声明示例
首先我们看下如下利用配置文件声明一个Bean,并且通过ClassPathXmlApplicationContext读取该Bean的过程:
1public class MockBusinessObject {} 2 3 4<?xml version="1.0" encoding="UTF-8"?> 5<beans xmlns="http://www.springframework.org/schema/beans" 6 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 8 9 <bean id="mockBO" class="MockBusinessObject"/> 10</beans>
通过上述方式,我们就创建了一个MockBusinessObject的实例,通过如下代码我们即可获取该实例,并且使用该实例完成我们所需要的工作:
1public class BeanApp { 2 public static void main(String[] args) { 3 ApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); 4 MockBusinessObject business = context.getBean(MockBusinessObject.class); 5 System.out.println(business); 6 } 7}
这里我们选用的IoC容器是ClassPathXmlApplicationContext,Spring有两种类型的Bean工厂:ApplicationContext和BeanFactory。这里ApplicationContext是继承自BeanFactory的,因而其具有BeanFactory的全部功能。ApplicationContext和BeanFactory的主要区别有两点:①ApplicationContext在注册Bean之后还会立即初始化各个Bean的实例,BeanFactory只有在调用getBean()方法时才会开始实例化各个Bean;②ApplicationContext会自动检测配置文件中声明的BeanFactoryPostProcessor和BeanPostProcessor等实例,并且在实例化各个Bean的时候会自动调用这些配置文件中声明的辅助bean实例,而BeanFactory必须手动调用其相应的方法才能将声明的辅助Bean添加到IoC容器中。
2. 源码解析
2.1 初始化BeanFactory信息
我们这里以ClassPathXmlApplicationContext为例,首先查看在构造该实例时Spring所做的工作:
1public ClassPathXmlApplicationContext( 2 String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) 3 throws BeansException { 4 5 super(parent); 6 setConfigLocations(configLocations); // 设置属性文件路径等 7 if (refresh) { 8 refresh(); // bean的注册和初始化 9 } 10}
通过跟踪其源码,我们最终看到上述代码,setConfigLocations()方法主要是对设置配置文件的路径,并且会对配置文件路径中的占位符使用属性文件中相关的属性进行替换。这里的refresh()方法则主要是进行bean的注册和初始化的,跟踪其代码如下:
1@Override 2public void refresh() throws BeansException, IllegalStateException { 3 synchronized (this.startupShutdownMonitor) { 4 // 准备Bean初始化相关的环境信息,其内部提供了一个空实现的initPropertySources()方法用于提供给用户一个更改相关环境信息的机会 5 prepareRefresh(); 6 7 // 创建BeanFactory实例,并且注册xml文件中相关的bean信息 8 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 9 10 // 注册Aware和Processor实例,并且注册了后续处理请求所需的一些Editor信息 11 prepareBeanFactory(beanFactory); 12 13 try { 14 // 提供的一个空方法,用于供给子类对已经生成的BeanFactory的一些信息进行定制 15 postProcessBeanFactory(beanFactory); 16 17 // 调用BeanFactoryPostProcessor及其子接口的相关方法,这些接口提供了一个入口,提供给了调用方一个修改已经生成的BeanDefinition的入口 18 invokeBeanFactoryPostProcessors(beanFactory); 19 20 // 对BeanPostProcessor进行注册 21 registerBeanPostProcessors(beanFactory); 22 23 // 初始化国际化所需的bean信息 24 initMessageSource(); 25 26 // 初始化事件广播器的bean信息 27 initApplicationEventMulticaster(); 28 29 // 提供的一个空方法,供给子类用于提供自定义的bean信息,或者修改已有的bean信息 30 onRefresh(); 31 32 // 注册事件监听器 33 registerListeners(); 34 35 // 对已经注册的非延迟(配置文件指定)bean的实例化 36 finishBeanFactoryInitialization(beanFactory); 37 38 // 清除缓存的资源信息,初始化一些声明周期相关的bean,并且发布Context已被初始化的事件 39 finishRefresh(); 40 } 41 42 catch (BeansException ex) { 43 if (logger.isWarnEnabled()) { 44 logger.warn("Exception encountered during context initialization - " + 45 "cancelling refresh attempt: " + ex); 46 } 47 48 // 发生异常则销毁已经生成的bean 49 destroyBeans(); 50 51 // 重置refresh字段信息 52 cancelRefresh(ex); 53 54 throw ex; 55 } 56 57 finally { 58 // 初始化一些缓存信息 59 resetCommonCaches(); 60 } 61 } 62}
可以看到,refresh()方法主要做了如下几个工作:
- BeanFactory的初始化,并且加载配置文件中相关bean的信息;
- BeanFactoryPostProcessor和BeanPostProcessor和调用;
- 初始化国际化信息;
- 注册和调用相关的监听器;
- 实例化注册的Bean信息;
对于bean所需实例化信息的注册,我们主要关注obtainFreshBeanFactory()方法,逐步跟踪其代码如下:
1protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { 2 refreshBeanFactory(); // 初始化BeanFactory并加载xml文件信息 3 // 获取已生成的BeanFactory 4 ConfigurableListableBeanFactory beanFactory = getBeanFactory(); 5 if (logger.isDebugEnabled()) { 6 logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); 7 } 8 return beanFactory; 9}
这里我们跟踪refreshBeanFactory()方法如下:
1@Override 2protected final void refreshBeanFactory() throws BeansException { 3 if (hasBeanFactory()) { // 如果BeanFactory已经创建则对其进行销毁 4 destroyBeans(); 5 closeBeanFactory(); 6 } 7 try { 8 // 创建BeanFactory实例 9 DefaultListableBeanFactory beanFactory = createBeanFactory(); 10 beanFactory.setSerializationId(getId()); // 为当前BeanFactory设置一个标识id 11 customizeBeanFactory(beanFactory); // 设置BeanFacotry的定制化属性信息 12 loadBeanDefinitions(beanFactory); // 加载xml文件信息 13 synchronized (this.beanFactoryMonitor) { 14 this.beanFactory = beanFactory; 15 } 16 } 17 catch (IOException ex) { 18 throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); 19 } 20}
可以看到,这里的xml加载主要是在loadBeanDefinitions()方法中,跟踪该方法如下:
1@Override 2protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { 3 // 创建一个XmlBeanDefinitionReader用于读取xml文件中的属性 4 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); 5 6 // 设置一些环境变量相关的信息 7 beanDefinitionReader.setEnvironment(this.getEnvironment()); 8 beanDefinitionReader.setResourceLoader(this); 9 beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); 10 11 // 提供的一个可供子类继承的方法,用于定制XmlBeanDefinitionReader相关的信息 12 initBeanDefinitionReader(beanDefinitionReader); 13 // 加载xml文件中的信息 14 loadBeanDefinitions(beanDefinitionReader); 15}
可以看到,这里xml文件中的bean信息,Spring主要是委托给了XmlBeanDefinitionReader来进行。如下是继续跟踪loadBeanDefinitions()方法的代码:
1protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { 2 Resource[] configResources = getConfigResources(); 3 if (configResources != null) { 4 reader.loadBeanDefinitions(configResources); 5 } 6 String[] configLocations = getConfigLocations(); 7 if (configLocations != null) { 8 reader.loadBeanDefinitions(configLocations); 9 } 10} 11 12 13@Override 14public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException { 15 Assert.notNull(resources, "Resource array must not be null"); 16 int counter = 0; 17 for (Resource resource : resources) { 18 counter += loadBeanDefinitions(resource); 19 } 20 return counter; 21}
这里XmlBeanDefinitionReader会依次读取所指定的每个配置文件的bean信息,继续跟踪loadBeanDefinitions()如下:
1public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { 2 Assert.notNull(encodedResource, "EncodedResource must not be null"); 3 if (logger.isInfoEnabled()) { 4 logger.info("Loading XML bean definitions from " + encodedResource.getResource()); 5 } 6 7 Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get(); 8 if (currentResources == null) { 9 currentResources = new HashSet<>(4); 10 this.resourcesCurrentlyBeingLoaded.set(currentResources); 11 } 12 if (!currentResources.add(encodedResource)) { 13 throw new BeanDefinitionStoreException( 14 "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); 15 } 16 try { 17 InputStream inputStream = encodedResource.getResource().getInputStream(); 18 try { 19 InputSource inputSource = new InputSource(inputStream); 20 if (encodedResource.getEncoding() != null) { 21 inputSource.setEncoding(encodedResource.getEncoding()); 22 } 23 return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); 24 } 25 finally { 26 inputStream.close(); 27 } 28 } 29 catch (IOException ex) { 30 throw new BeanDefinitionStoreException( 31 "IOException parsing XML document from " + encodedResource.getResource(), ex); 32 } 33 finally { 34 currentResources.remove(encodedResource); 35 if (currentResources.isEmpty()) { 36 this.resourcesCurrentlyBeingLoaded.remove(); 37 } 38 } 39}
上述代码中,主要是将xml文件转换为了一个InputStream,最终通过调用doLoadBeanDefinitions()方法进行bean信息的注册。如下是doLoadBeanDefinitions()方法的实现:
1protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) 2 throws BeanDefinitionStoreException { 3 try { 4 Document doc = doLoadDocument(inputSource, resource); 5 return registerBeanDefinitions(doc, resource); 6 } 7 catch (BeanDefinitionStoreException ex) { 8 throw ex; 9 } 10 catch (SAXParseException ex) { 11 throw new XmlBeanDefinitionStoreException(resource.getDescription(), "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex); 12 } 13 catch (SAXException ex) { 14 throw new XmlBeanDefinitionStoreException(resource.getDescription(), "XML document from " + resource + " is invalid", ex); 15 } 16 catch (ParserConfigurationException ex) { 17 throw new BeanDefinitionStoreException(resource.getDescription(), "Parser configuration exception parsing XML from " + resource, ex); 18 } 19 catch (IOException ex) { 20 throw new BeanDefinitionStoreException(resource.getDescription(), "IOException parsing XML document from " + resource, ex); 21 } 22 catch (Throwable ex) { 23 throw new BeanDefinitionStoreException(resource.getDescription(), "Unexpected exception parsing XML document from " + resource, ex); 24 } 25}
上述代码中,首先将资源文件转换为一个Document对象,该对象中保存有各个xml文件中各个节点和子节点的相关信息。通过转换得到的Document对象,通过registerBeanDefinitions()方法完成Bean的注册,如下是registerBeanDefinitions()方法的代码:
1public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException { 2 BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); 3 int countBefore = getRegistry().getBeanDefinitionCount(); 4 documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); 5 return getRegistry().getBeanDefinitionCount() - countBefore; 6}
如下是BeanDefinitionDocumentReader.registerBeanDefinitions()方法的实现:
1@Override 2public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { 3 this.readerContext = readerContext; 4 logger.debug("Loading bean definitions"); 5 Element root = doc.getDocumentElement(); 6 doRegisterBeanDefinitions(root); 7}
2.2 解析xml文件
这里首先通过Document对象获取到xml文件的根节点信息,然后通过doRegisterBeanDefinitions()方法转换节点的bean信息:
1protected void doRegisterBeanDefinitions(Element root) { 2 BeanDefinitionParserDelegate parent = this.delegate; 3 this.delegate = createDelegate(getReaderContext(), root, parent); 4 5 if (this.delegate.isDefaultNamespace(root)) { 6 String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE); 7 if (StringUtils.hasText(profileSpec)) { 8 String[] specifiedProfiles = StringUtils.tokenizeToStringArray( 9 profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); 10 if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) { 11 if (logger.isInfoEnabled()) { 12 logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec + "] not matching: " + getReaderContext().getResource()); 13 } 14 return; 15 } 16 } 17 } 18 19 preProcessXml(root); 20 parseBeanDefinitions(root, this.delegate); 21 postProcessXml(root); 22 23 this.delegate = parent; 24}
在doRegisterBeanDefinitions()方法中,其首先获取当前xml文件是否为默认的命名空间,也即是否使用的是Spring的xsd文件声明的bean,如果是的,则获取当前是否有指定profile相关的信息,并且在环境变量中获取当前是哪种profile,与命名空间中指定的profile进行比较,如果profile不匹配,则过滤掉当前的xml文件。
下面的preProcessorXml()和postProcessorXml()方法是两个空方法,用于供给子类实现从而对获取到的Document对象进行定制。真正的bean节点的读取在parseBeanDefinitions()方法中:
1protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { 2 if (delegate.isDefaultNamespace(root)) { 3 NodeList nl = root.getChildNodes(); 4 for (int i = 0; i < nl.getLength(); i++) { 5 Node node = nl.item(i); 6 if (node instanceof Element) { 7 Element ele = (Element) node; 8 if (delegate.isDefaultNamespace(ele)) { 9 parseDefaultElement(ele, delegate); 10 } 11 else { 12 delegate.parseCustomElement(ele); 13 } 14 } 15 } 16 } 17 else { 18 delegate.parseCustomElement(root); 19 } 20}
这里在读取bean节点的时候分为了两种情形进行读取:①默认的命名空间,也即Spring所提供的xsd命名空间的bean读取;②自定义的命名空间定义的bean读取。关于自定义命名空间bean的读取我们在后续文章中会进行讲解,本文主要讲解使用Spring默认命名空间所定义的bean的读取。如下是parseDefaultElement()方法的实现:
1private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { 2 if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { 3 importBeanDefinitionResource(ele); 4 } else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { 5 processAliasRegistration(ele); 6 } else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { 7 processBeanDefinition(ele, delegate); 8 } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { 9 doRegisterBeanDefinitions(ele); 10 } 11}
可以看到,在对xml节点的读取的时候,其分为了四种情形:①读取import节点所指定的xml文件信息;②读取alias节点的信息;③读取bean节点指定的信息;④读取嵌套bean的信息。由于这里对bean节点的解析是较为复杂,并且最为重要的,本文主要对其余三种节点的解析进行讲解,对bean节点的解析将放入下一篇文章进行讲解。
2.2.1 读取import节点指定的bean信息
1protected void importBeanDefinitionResource(Element ele) { 2 String location = ele.getAttribute(RESOURCE_ATTRIBUTE); 3 if (!StringUtils.hasText(location)) { 4 getReaderContext().error("Resource location must not be empty", ele); 5 return; 6 } 7 8 // 处理import节点指定的路径中的属性占位符,将其替换为属性文件中指定属性值 9 location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location); 10 11 Set<Resource> actualResources = new LinkedHashSet<>(4); 12 13 // 处理路径信息,判断其为相对路径还是绝对路径 14 boolean absoluteLocation = false; 15 try { 16 absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute(); 17 } catch (URISyntaxException ex) {} 18 19 if (absoluteLocation) { // 如果是绝对路径,则直接读取该文件 20 try { 21 // 递归调用loadBeanDefinitions()方法加载import所指定的文件中的bean信息 22 int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources); 23 if (logger.isDebugEnabled()) { 24 logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]"); 25 } 26 } catch (BeanDefinitionStoreException ex) { 27 getReaderContext().error( 28 "Failed to import bean definitions from URL location [" + location + "]", ele, ex); 29 } 30 } 31 else { 32 try { 33 int importCount; 34 Resource relativeResource = getReaderContext().getResource() 35 .createRelative(location); // 判断是否为相对路径 36 // 如果是相对路径,则调用loadBeanDefinitions()方法加载该文件中的bean信息 37 if (relativeResource.exists()) { 38 importCount = getReaderContext().getReader() 39 .loadBeanDefinitions(relativeResource); 40 actualResources.add(relativeResource); 41 } 42 else { 43 // 如果相对路径,也不是绝对路径,则将该路径当做一个外部url进行请求读取 44 String baseLocation = getReaderContext().getResource() 45 .getURL().toString(); 46 // 继续调用loadBeanDefinitions()方法读取下载得到的xml文件信息 47 importCount = getReaderContext().getReader().loadBeanDefinitions( 48 StringUtils.applyRelativePath(baseLocation, location), actualResources); 49 } 50 if (logger.isDebugEnabled()) { 51 logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]"); 52 } 53 } catch (IOException ex) { 54 getReaderContext().error("Failed to resolve current resource location", ele, ex); 55 } catch (BeanDefinitionStoreException ex) { 56 getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]", 57 ele, ex); 58 } 59 } 60 Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]); 61 // 调用注册的对import文件读取完成事件的监听器 62 getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele)); 63}
可以看到,对import节点的解析,主要思路还是判断import节点中指定的路径是相对路径还是绝对路径,如果都不是,则将其作为一个外部URL进行读取,最终将读取得到的文件还是使用loadBeanDefinitions()进行递归调用读取该文件中的bean信息。
2.2.2 读取alias节点指定的信息
1protected void processAliasRegistration(Element ele) { 2 String name = ele.getAttribute(NAME_ATTRIBUTE); // 获取name属性的值 3 String alias = ele.getAttribute(ALIAS_ATTRIBUTE); // 获取alias属性的值 4 boolean valid = true; 5 if (!StringUtils.hasText(name)) { 6 getReaderContext().error("Name must not be empty", ele); 7 valid = false; 8 } 9 if (!StringUtils.hasText(alias)) { 10 getReaderContext().error("Alias must not be empty", ele); 11 valid = false; 12 } 13 if (valid) { 14 try { 15 // 注册别名信息 16 getReaderContext().getRegistry().registerAlias(name, alias); 17 } 18 catch (Exception ex) { 19 getReaderContext().error("Failed to register alias '" + alias + 20 "' for bean with name '" + name + "'", ele, ex); 21 } 22 // 激活对alias注册完成进行监听的监听器 23 getReaderContext().fireAliasRegistered(name, alias, extractSource(ele)); 24 } 25}
如下是registerAlias()方法的最终实现:
1@Override 2public void registerAlias(String name, String alias) { 3 Assert.hasText(name, "'name' must not be empty"); 4 Assert.hasText(alias, "'alias' must not be empty"); 5 if (alias.equals(name)) { 6 this.aliasMap.remove(alias); 7 } 8 else { 9 String registeredName = this.aliasMap.get(alias); 10 if (registeredName != null) { 11 if (registeredName.equals(name)) { 12 // 如果已注册,则直接返回 13 return; 14 } 15 if (!allowAliasOverriding()) { 16 throw new IllegalStateException("Cannot register alias '" + alias + "' for name '" + name + "': It is already registered for name '" + registeredName + "'."); 17 } 18 } 19 // 检查是否有循环别名注册 20 checkForAliasCircle(name, alias); 21 // 将别名作为key,目标bean名称作为值注册到存储别名的Map中 22 this.aliasMap.put(alias, name); 23 } 24}
可以看到,别名的注册,其实就是将别名作为一个key,将目标bean的名称作为值,存储到一个Map中。这里需要注意的是,目标bean的名称也可能是一个别名。
2.2.3 读取嵌套beans信息
对于嵌套beans的解析,可以看到,其调用的是doRegisterBeanDefinitions()方法,该方法正是前面我们讲解的开始对bean解析的方法,因而这里其实是使用递归对嵌套bean进行解析的。这里需要说明的是,一个xml文件,其根节点其实就是一个beans节点,而嵌套beans节点的节点名也是beans,因而嵌套beans其实也可以理解为一份单独引入的xml文件,因而可以使用递归的方式对其进行读取。
3. 广告
读者朋友如果觉得本文还不错,可以点击下面的广告链接,这可以为作者带来一定的收入,从而激励作者创作更好的文章,非常感谢!