以一個簡單的例子開頭:
情境類 Client.java
package com.dusk.bean;import org.junit.Test;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.Resource;public class Client {@Testpublic void test(){Resource resource=new ClassPathResource("com/dusk/bean/bean.xml");BeanFactory beanFactory=new XmlBeanFactory(resource);Hello hello=beanFactory.getBean(Hello.class);hello.sayHello();}}
Bean實體類 Hello.java
package com.dusk.bean;public class Hello {private String name;public void setName(String name) {this.name = name;}public void sayHello(){System.out.println("hello, "+name+"!");}}
設定檔bean.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="hello" class="com.dusk.bean.Hello"><property name="name" value="dusk"/></bean></beans>
當然了輸出結果是:
hello, dusk!
接下來我們研究一下XML配置的載入過程。
1. ClassPathResource用於指向一個類路徑下的一個資源,這裡的com/dusk/bean/bean.xml表示的是包含Spring bean配置的XML檔案。
public class XmlBeanFactory extends DefaultListableBeanFactory {private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);/** * Create a new XmlBeanFactory with the given resource, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @throws BeansException in case of loading or parsing errors */public XmlBeanFactory(Resource resource) throws BeansException {this(resource, null);}/** * Create a new XmlBeanFactory with the given input stream, * which must be parsable using DOM. * @param resource XML resource to load bean definitions from * @param parentBeanFactory parent bean factory * @throws BeansException in case of loading or parsing errors */public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {super(parentBeanFactory);<strong>this.reader.loadBeanDefinitions(resource);</strong>}}
通過上面的加粗代碼可以知道設定檔是由XmlBeanDefinitionReader載入的。先說明一下,Spring的XML設定檔是由SAX處理的。關於SAX可以參考博文
SAX詳解。
畫了一個簡單的順序圖表,有順序圖表的使用問題歡迎指正。
我們可以從圖中看出來解析XML主要是由org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader類完成,這是Spring提供的預設解析類,當然你也可以定製自己的解析。
可以看出來Spring提供了一個很好的增強機制讓你增強這個類,有兩個空的方法預留給開發人員。
/** * 解析自訂元素的地方 * <p>Allow the XML to be extensible by processing any custom element types first, * before we start to process the bean definitions. This method is a natural * extension point for any other custom pre-processing of the XML. * <p>The default implementation is empty. Subclasses can override this method to * convert custom elements into standard Spring bean definitions, for example. * Implementors have access to the parser's bean definition reader and the * underlying XML resource, through the corresponding accessors. * @see #getReaderContext() */protected void preProcessXml(Element root) {}和
/** * Allow the XML to be extensible by processing any custom element types last, * after we finished processing the bean definitions. This method is a natural * extension point for any other custom post-processing of the XML. * <p>The default implementation is empty. Subclasses can override this method to * convert custom elements into standard Spring bean definitions, for example. * Implementors have access to the parser's bean definition reader and the * underlying XML resource, through the corresponding accessors. * @see #getReaderContext() */protected void postProcessXml(Element root) {}
這兩個方法都是protected的,為了方便子類重寫,並且都是空方法。
主要的解析XML方法是parseBeanDefinitions,如下:
/** * Parse the elements at the root level in the document: * "import", "alias", "bean". * @param root the DOM root element of the document */protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {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)) {parseDefaultElement(ele, delegate);}else {delegate.parseCustomElement(ele);}}}}else {delegate.parseCustomElement(root);}}
可以看出來它是迴圈處理的,接著看詳細內容:
/* * 解析過程,對預設的元素進行分析比如,bean */private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {//import元素importBeanDefinitionResource(ele);}else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {//alias元素processAliasRegistration(ele);}else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {//bean元素processBeanDefinition(ele, delegate);}else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {//beans元素// recurse(遞迴)doRegisterBeanDefinitions(ele);}}
以及
/** * Parse an "import" element and load the bean definitions * from the given resource into the bean factory. */protected void importBeanDefinitionResource(Element ele) {String location = ele.getAttribute(RESOURCE_ATTRIBUTE);if (!StringUtils.hasText(location)) {getReaderContext().error("Resource location must not be empty", ele);return;}// Resolve system properties: e.g. "${user.dir}"location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);Set<Resource> actualResources = new LinkedHashSet<Resource>(4);// Discover whether the location is an absolute or relative URIboolean absoluteLocation = false;try {absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();}catch (URISyntaxException ex) {// cannot convert to an URI, considering the location relative// unless it is the well-known Spring prefix "classpath*:"}// Absolute or relative?if (absoluteLocation) {try {int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);if (logger.isDebugEnabled()) {logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");}}catch (BeanDefinitionStoreException ex) {getReaderContext().error("Failed to import bean definitions from URL location [" + location + "]", ele, ex);}}else {// No URL -> considering resource location as relative to the current file.try {int importCount;Resource relativeResource = getReaderContext().getResource().createRelative(location);if (relativeResource.exists()) {importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);actualResources.add(relativeResource);}else {String baseLocation = getReaderContext().getResource().getURL().toString();importCount = getReaderContext().getReader().loadBeanDefinitions(StringUtils.applyRelativePath(baseLocation, location), actualResources);}if (logger.isDebugEnabled()) {logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");}}catch (IOException ex) {getReaderContext().error("Failed to resolve current resource location", ele, ex);}catch (BeanDefinitionStoreException ex) {getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",ele, ex);}}Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));}/** * Process the given alias element, registering the alias with the registry. */protected void processAliasRegistration(Element ele) {String name = ele.getAttribute(NAME_ATTRIBUTE);String alias = ele.getAttribute(ALIAS_ATTRIBUTE);boolean valid = true;if (!StringUtils.hasText(name)) {getReaderContext().error("Name must not be empty", ele);valid = false;}if (!StringUtils.hasText(alias)) {getReaderContext().error("Alias must not be empty", ele);valid = false;}if (valid) {try {getReaderContext().getRegistry().registerAlias(name, alias);}catch (Exception ex) {getReaderContext().error("Failed to register alias '" + alias +"' for bean with name '" + name + "'", ele, ex);}getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));}}
/** * Process the given bean element, parsing the bean definition * and registering it with the registry. */protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);if (bdHolder != null) {bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);try {//像BeanFactory中註冊bean定義// 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);}<strong>//向IoC容器發送事件,表示解析和註冊完成// Send registration event.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));</strong>}}以上就是Spring預設的解析XML的步驟。
想要人前顯貴必先人後受罪。