通過 Debug 運行 XmlBeanDefinitionReaderTests 類的 withFreshInputStream() 的方法,調試 Spring 解析 XML 配置文件,獲得 Bean 的定義。
大體流程可根據序號查看,xml 配置文件隨便看一眼,不用過多在意。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "https://www.springframework.org/dtd/spring-beans-2.0.dtd"><beans><bean id="validEmptyWithDescription" class="org.springframework.beans.testfixture.beans.TestBean"><description>I have no properties and I'm happy without them.</description></bean><!--Check automatic creation of alias, to allow for names that are illegal as XML ids.--><bean id="aliased" class=" org.springframework.beans.testfixture.beans.TestBean " name="myalias"><property name="name"><value>aliased</value></property></bean><alias name="aliased" alias="youralias"/><alias name="multiAliased" alias="alias3"/><bean id="multiAliased" class="org.springframework.beans.testfixture.beans.TestBean" name="alias1,alias2"><property name="name"><value>aliased</value></property></bean><alias name="multiAliased" alias="alias4"/><bean class="org.springframework.beans.testfixture.beans.TestBean" name="aliasWithoutId1,aliasWithoutId2,aliasWithoutId3"><property name="name"><value>aliased</value></property></bean><bean class="org.springframework.beans.testfixture.beans.TestBean"><property name="name"><null/></property></bean><bean class="org.springframework.beans.factory.xml.DummyReferencer"/><bean class="org.springframework.beans.factory.xml.DummyReferencer"/><bean class="org.springframework.beans.factory.xml.DummyReferencer"/><bean id="rod" class="org.springframework.beans.testfixture.beans.TestBean"><property name="name"><value><!-- a comment -->Rod</value></property><property name="age"><value>31</value></property><property name="spouse"><ref bean="father"/></property><property name="touchy"><value/></property></bean><bean id="roderick" parent="rod"><property name="name"><value>Roderick<!-- a comment --></value></property><!-- Should inherit age --></bean><bean id="kerry" class="org.springframework.beans.testfixture.beans.TestBean"><property name="name"><value>Ker<!-- a comment -->ry</value></property><property name="age"><value>34</value></property><property name="spouse"><ref bean="rod"/></property><property name="touchy"><value></value></property></bean><bean id="kathy" class="org.springframework.beans.testfixture.beans.TestBean" scope="prototype"><property name="name"><value>Kathy</value></property><property name="age"><value>28</value></property><property name="spouse"><ref bean="father"/></property></bean><bean id="typeMismatch" class="org.springframework.beans.testfixture.beans.TestBean" scope="prototype"><property name="name"><value>typeMismatch</value></property><property name="age"><value>34x</value></property><property name="spouse"><ref bean="rod"/></property></bean><!-- Test of lifecycle callbacks --><bean id="mustBeInitialized" class="org.springframework.beans.testfixture.beans.MustBeInitialized"/><bean id="lifecycle" class="org.springframework.beans.testfixture.beans.LifecycleBean"init-method="declaredInitMethod"><property name="initMethodDeclared"><value>true</value></property></bean><bean id="protectedLifecycle" class="org.springframework.beans.factory.xml.ProtectedLifecycleBean"init-method="declaredInitMethod"><property name="initMethodDeclared"><value>true</value></property></bean><!-- Factory beans are automatically treated differently --><bean id="singletonFactory" class="org.springframework.beans.testfixture.beans.factory.DummyFactory"></bean><bean id="prototypeFactory" class="org.springframework.beans.testfixture.beans.factory.DummyFactory"><property name="singleton"><value>false</value></property></bean><!-- Check that the circular reference resolution mechanism doesn't breakrepeated references to the same FactoryBean --><bean id="factoryReferencer" class="org.springframework.beans.factory.xml.DummyReferencer"><property name="testBean1"><ref bean="singletonFactory"/></property><property name="testBean2"><ref bean="singletonFactory"/></property><property name="dummyFactory"><ref bean="&singletonFactory"/></property></bean><bean id="factoryReferencerWithConstructor" class="org.springframework.beans.factory.xml.DummyReferencer"><constructor-arg><ref bean="&singletonFactory"/></constructor-arg><property name="testBean1"><ref bean="singletonFactory"/></property><property name="testBean2"><ref bean="singletonFactory"/></property></bean><!-- Check that the circular reference resolution mechanism doesn't breakprototype instantiation --><bean id="prototypeReferencer" class="org.springframework.beans.factory.xml.DummyReferencer" scope="prototype"><property name="testBean1"><ref bean="kathy"/></property><property name="testBean2"><ref bean="kathy"/></property></bean><bean id="listenerVeto" class="org.springframework.beans.testfixture.beans.TestBean"><property name="name"><value>listenerVeto</value></property><property name="age"><value>66</value></property></bean><bean id="validEmpty" class="org.springframework.beans.testfixture.beans.TestBean"/><bean id="commentsInValue" class="org.springframework.beans.testfixture.beans.TestBean"><property name="name"><value>this is<!-- don't mind me --> a <![CDATA[<!--comment-->]]></value></property></bean></beans>
@Testpublic void withFreshInputStream() {// TODO 1.創建 SimpleBeanDefinitionRegistry 對象,提供注冊BeanDefinition功能SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();// TODO 2.獲取配置文件Resource resource = new ClassPathResource("test.xml", getClass());// TODO 3.創建 XmlBeanDefinitionReader 對象,提供讀取 XMl 文件中的 Bean 的定義信息;new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource);// TODO 30.驗證 BeanDefinitions 信息;testBeanDefinitions(registry);System.out.println("success");}private void testBeanDefinitions(BeanDefinitionRegistry registry) {assertThat(registry.getBeanDefinitionCount()).isEqualTo(24);assertThat(registry.getBeanDefinitionNames().length).isEqualTo(24);assertThat(Arrays.asList(registry.getBeanDefinitionNames()).contains("rod")).isTrue();assertThat(Arrays.asList(registry.getBeanDefinitionNames()).contains("aliased")).isTrue();assertThat(registry.containsBeanDefinition("rod")).isTrue();assertThat(registry.containsBeanDefinition("aliased")).isTrue();assertThat(registry.getBeanDefinition("rod").getBeanClassName()).isEqualTo(TestBean.class.getName());assertThat(registry.getBeanDefinition("aliased").getBeanClassName()).isEqualTo(TestBean.class.getName());assertThat(registry.isAlias("youralias")).isTrue();String[] aliases = registry.getAliases("aliased");assertThat(aliases.length).isEqualTo(2);assertThat(ObjectUtils.containsElement(aliases, "myalias")).isTrue();assertThat(ObjectUtils.containsElement(aliases, "youralias")).isTrue();}
/*** Load bean definitions from the specified XML file.* @param resource the resource descriptor for the XML file* @return the number of bean definitions found* @throws BeanDefinitionStoreException in case of loading or parsing errors** TODO XmlBeanDefinitionReader加載資源的入口方法*/@Overridepublic int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {// TODO 4.將讀取的XML資源進行特殊的編碼處理return loadBeanDefinitions(new EncodedResource(resource));}
/*** Load bean definitions from the specified XML file.* @param encodedResource the resource descriptor for the XML file,* allowing to specify an encoding to use for parsing the file* @return the number of bean definitions found* @throws BeanDefinitionStoreException in case of loading or parsing errors** TODO 這里載入XML形式Bean配置信息方法*/public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {Assert.notNull(encodedResource, "EncodedResource must not be null");if (logger.isTraceEnabled()) {logger.trace("Loading XML bean definitions from " + encodedResource);}Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();if (!currentResources.add(encodedResource)) {throw new BeanDefinitionStoreException("Detected cyclic loading of " + encodedResource + " - check your import definitions!");}// TODO 5. 將資源文件轉為InputStream的I/O流try (InputStream inputStream = encodedResource.getResource().getInputStream()) { // TODO 只有是Closeable的子類才能這樣書寫,有點是系統會自動幫助我們關閉// TODO 從InputStream中得到XML的解析源InputSource inputSource = new InputSource(inputStream);if (encodedResource.getEncoding() != null) {inputSource.setEncoding(encodedResource.getEncoding());}// TODO 6.具體讀取過程return doLoadBeanDefinitions(inputSource, encodedResource.getResource());}catch (IOException ex) {throw new BeanDefinitionStoreException("IOException parsing XML document from " + encodedResource.getResource(), ex);}finally {// TODO 29. currentResources.remove(encodedResource);if (currentResources.isEmpty()) {this.resourcesCurrentlyBeingLoaded.remove();}}}
/*** Actually load bean definitions from the specified XML file.* @param inputSource the SAX InputSource to read from* @param resource the resource descriptor for the XML file* @return the number of bean definitions found* @throws BeanDefinitionStoreException in case of loading or parsing errors* @see #doLoadDocument* @see #registerBeanDefinitions***/protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)throws BeanDefinitionStoreException {try {// TODO 7. 加載Bean配置信息,并轉換為文檔對象Document doc = doLoadDocument(inputSource, resource);// TODO 8. 對Bean定義進行解析int count = registerBeanDefinitions(doc, resource);if (logger.isDebugEnabled()) {logger.debug("Loaded " + count + " bean definitions from " + resource);}return count;}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);}}
/*** Register the bean definitions contained in the given DOM document.* Called by {@code loadBeanDefinitions}.* <p>Creates a new instance of the parser class and invokes* {@code registerBeanDefinitions} on it.* @param doc the DOM document* @param resource the resource descriptor (for context information)* @return the number of bean definitions found* @throws BeanDefinitionStoreException in case of parsing errors* @see #loadBeanDefinitions* @see #setDocumentReaderClass* @see BeanDefinitionDocumentReader#registerBeanDefinitions** TODO 按照Spring的Bean語義要求將Bean配置信息解析并轉換為內部數據結構**/public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {// TODO 9.得到BeanDefinitionDoucumentReader來對XML格式的BeanDefinition進行解析BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();// TODO 10.獲得容器中注冊的Bean數量int countBefore = getRegistry().getBeanDefinitionCount();// TODO 11. 解析過程的入口,這里使用了委派模式,BeanDefinitionDocumentReader只是一個接口// TODO 具體的解析過程由實現類DefaultBeanDefinitionDocumentReader完成documentReader.registerBeanDefinitions(doc, createReaderContext(resource));// TODO 28. 統計解析的Bean數量return getRegistry().getBeanDefinitionCount() - countBefore;}
/*** This implementation parses bean definitions according to the "spring-beans" XSD* (or DTD, historically).* <p>Opens a DOM Document; then initializes the default settings* specified at the {@code <beans/>} level; then parses the contained bean definitions.** TODO 根據Spring DTD對Bean的定義規則解析Bean定義的文檔對象*/@Overridepublic void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {// TODO 獲得XML描述符this.readerContext = readerContext;// TODO 12. doc.getDocumentElement() 獲的Document根元素doRegisterBeanDefinitions(doc.getDocumentElement());}
/*** Register each bean definition within the given root {@code <beans/>} element.*/@SuppressWarnings("deprecation") // for Environment.acceptsProfiles(String...)protected void doRegisterBeanDefinitions(Element root) {// Any nested <beans> elements will cause recursion in this method. In// order to propagate and preserve <beans> default-* attributes correctly,// keep track of the current (parent) delegate, which may be null. Create// the new (child) delegate with a reference to the parent for fallback purposes,// then ultimately reset this.delegate back to its original (parent) reference.// this behavior emulates a stack of delegates without actually necessitating one.// TODO 具體的解析過程由BeanDefinitionParserDelegate實現// TODO BeanDefinitionParserDelegate中定義了Spring Bean定義XML文件的各元素BeanDefinitionParserDelegate parent = this.delegate;this.delegate = createDelegate(getReaderContext(), root, parent);// TODO 校驗是否引入 beans schemaLocationif (this.delegate.isDefaultNamespace(root)) {String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);if (StringUtils.hasText(profileSpec)) {String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);// We cannot use Profiles.of(...) since profile expressions are not supported// in XML config. See SPR-12458 for details.if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {if (logger.isDebugEnabled()) {logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +"] not matching: " + getReaderContext().getResource());}return;}}}// TODO 在解析Bean定義之前,進行自定義解析,增強解析過程的可擴展性preProcessXml(root);// TODO 12.從文檔的根元素開始進行Bean定義的文檔對象的解析parseBeanDefinitions(root, this.delegate);// TODO 27.在解析Bean定義之后,進行自定義解析,增強解析過程的可擴展性postProcessXml(root);this.delegate = parent;}
/*** Parse the elements at the root level in the document:* "import", "alias", "bean".* @param root the DOM root element of the document** TODO 使用Spring的Bean規則從文檔的根元素開始Bean定義的文檔對象的解析*/protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {// TODO 13. Bean定義的文檔對象使用了Spring默認的XML命名空間if (delegate.isDefaultNamespace(root)) {// TODO 14. 獲取Bean定義的文檔對象根元素的所有子節點NodeList nl = root.getChildNodes();// TODO 此處是循環,忽略需要,需要是大體執行流程不是唯一for (int i = 0; i < nl.getLength(); i++) {Node node = nl.item(i);// TODO 15. 獲得的文檔節點是XML元素節點if (node instanceof Element ele) {// TODO 16. Bean定義的文檔的元素節點使用的是Spring默認的XML命名空間if (delegate.isDefaultNamespace(ele)) {// TODO 17. 使用Spring的Bean規則解析元素節點parseDefaultElement(ele, delegate);}else {// TODO 如果沒有使用Spring默認的XMl命名空間,則使用用戶自定義的規則解析元素節點delegate.parseCustomElement(ele);}}}}else {// TODO 如果沒有使用Spring默認的XMl命名空間,則使用用戶自定義的規則解析元素節點delegate.parseCustomElement(root);}}
/*** TODO 使用Spring的Bean規則解析文檔元素節點* @param ele* @param delegate*/private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {// TODO 18.如果節點是<import>導入元素,進行導入元素解析if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {importBeanDefinitionResource(ele);}// TODO 19.如果節點是<alias>別名元素,進行別名解析else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {processAliasRegistration(ele);}// TODO 20.如果節點是<bean>元素,則按照Spring的Bean規則解析元素else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {processBeanDefinition(ele, delegate);}// TODO 如果節點是<beans>元素,則按照Spring的Bean規則解析元素else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {// recursedoRegisterBeanDefinitions(ele);}}
/*** Process the given bean element, parsing the bean definition* and registering it with the registry.* TODO 解析Bean資源文檔對象的普通元素* TODO 示例:<bean id="testBean" class="org.springframework.beans.testfixture.beans.TestBean"/>*/protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);// TODO 21. BeanDefinitionHolder是對BeanDefinition的封裝,即Bean定義的封裝類// TODO 對文檔對象中<bean>元素的解析由BeanDefinitionParserDelegate實現// TODO BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);if (bdHolder != null) {bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);try {// 22.Register the final decorated instance.BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());}catch (BeanDefinitionStoreException ex) {getReaderContext().error("Failed to register bean definition with name '" +bdHolder.getBeanName() + "'", ele, ex);}// Send registration event.// TODO 26.在完成向Spring Ioc容器注冊解析得到的Bean定義之后,發送注冊事件getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));}}
/*** Register the given bean definition with the given bean factory.* @param definitionHolder the bean definition including name and aliases* @param registry the bean factory to register with* @throws BeanDefinitionStoreException if registration failed** TODO 將解析的BeanDefinitionHole注冊到Spring Ioc容器*/public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)throws BeanDefinitionStoreException {// Register bean definition under primary name.// TODO 獲取解析的beanDefinition的名稱String beanName = definitionHolder.getBeanName();// TODO 23.向Spring Ioc容器注冊BeanDefinitionregistry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());// Register aliases for bean name, if any.// TODO 25.如果解析的BeanDefinition有別名,向Spring Ioc容器注冊別名String[] aliases = definitionHolder.getAliases();if (aliases != null) {for (String alias : aliases) {registry.registerAlias(beanName, alias);}}}
/*** TODO 注冊 BeanDefinition 信息*/@Overridepublic void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)throws BeanDefinitionStoreException {Assert.hasText(beanName, "'beanName' must not be empty");Assert.notNull(beanDefinition, "BeanDefinition must not be null");// TODO 24.存儲 BeanDefinition this.beanDefinitionMap.put(beanName, beanDefinition);}