这就是我们从之前的源码分析中理解到的,但这里实际还忽略了一个步骤,这也是之前分析时没讲到的,你能想到是什么么?我们设计的标签需不需要一个规范?不可能让其他人随便写,否则怎么识别呢?因此需要一个规范约束。同样,在Spring的META-INF文件夹下都会有一个spring.schemas文件,该文件和spring.handler文件一样,定义了约束文件和约束命名空间的映射关系,下面就是context的spring.schemas文件部分内容:
http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context.xsd ...... http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache.xsd但是这个文件是在什么时候被读取的呢?是不是应该在解析xml之前就把规范设置好?实际上就是在调用XmlBeanDefinitionReader的doLoadDocument方法时读取的该文件:
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception { return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler, getValidationModeForResource(resource), isNamespaceAware()); } protected EntityResolver getEntityResolver() { if (this.entityResolver == null) { // Determine default EntityResolver to use. ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader != null) { this.entityResolver = new ResourceEntityResolver(resourceLoader); } else { this.entityResolver = new DelegatingEntityResolver(getBeanClassLoader()); } } return this.entityResolver; } public DelegatingEntityResolver(@Nullable ClassLoader classLoader) { this.dtdResolver = new BeansDtdResolver(); this.schemaResolver = new PluggableSchemaResolver(classLoader); } public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/spring.schemas"; public PluggableSchemaResolver(@Nullable ClassLoader classLoader) { this.classLoader = classLoader; this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION; } 总结通过两篇文章完成了对Spring XML标签和注解解析的源码分析,整体流程多看几遍还是不复杂,关键是要学习到其中的设计思想:装饰、模板、委托、SPI;掌握其中我们可以使用到的扩展点:xml解析前后扩展、自定义标签扩展、自定义注解扩展(本篇没有讲解,可以思考一下);深刻理解BeanDefinition对象,可以看到所有标签和注解类都会封装为该对象,因此接下来对象实例化都是根据该对象进行的。