一、前言
在前面的博客中我们有介绍到refresh方法中的otainFreshBeanFaction方法,这个方法的作用就是获取bean工厂,在这期间还会完成配置文件的加载,生成BeanDefinition,需要注意的是这里生成的BeanFactory默认的是DefaultListableBeanFactory,需要注意的是,我们自定的一些xsd约束文件也是在这里完成解析,通过实现BeanDefitionParser接口,并且实现parse方法,自定义的标签也通过实现NamespaceHandlerSupport接口,并实现init方法。下面是我画的bean配置文件的解析流程图:
通过这一节博客的学习我们主要是看看spring是如何解析配置文件,并且知道是如何解析我们自定义的xsd,这样子以后如果我们要遇到一个需求需要自定义标签的解析就不会无从下手了。
二、Spring配置文件解析流程源码分析
2.1入库:obtainFreshBeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
/**
* 刷新bean工厂,判断bean工厂是否已经存在,如果存在需要进行销毁和关闭
* 默认调用的是AbstractRefreshableApplicationContext的refreshBeanFactory方法.
* 刷新Bean工厂时会进行bean定义的加载操作。
* 初始化BeanFactory,并进行XML文件读取,并将得到的BeanFactory记录在当前实体的属性中
*/
refreshBeanFactory();
return getBeanFactory();
}
我们接着往下看refreshBeanFactory方法:
@Override
protected final void refreshBeanFactory() throws BeansException {
// 判断bean工厂是否存在,如果存在需要先销毁和关闭。否则会出现问题
if (hasBeanFactory()) {
// 销毁bean,根据bean的名称将bean工厂中的所有bean都从map中移除
destroyBeans();
// 关闭bean工厂,设置Bean工厂的序列化id为null,并将beanFactory的值赋值为null
closeBeanFactory();
}
try {
// 重新创建bean工厂,默认返回的是Bean工厂类型是:DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 设置序列化ID,ID: class名称 + "@" + 对象的十六进制值
beanFactory.setSerializationId(getId());
// 定制bean工厂。作用:设置bean定义是否可以被覆盖以及设置bean在创建的时候是否允许循环引用.
customizeBeanFactory(beanFactory);
// 解析并加载bean的定义,默认是通过AbstractXmlApplicationContext类中的loadBeanDefinitions实现
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
该方法里面首先会去判断是否存在beanFactory,如果存在的话就先去销毁对应的factory,然后调用createBeanFactory创建一个bean工厂,默认给我们创建的DefaultListableBeanFactory,然后设置一些属性信息,其中在loadBeanFinitions里面就就是去解析配置文件。
2.2 loadBeanDefinitions(beanFactory)
创建一个xml格式的bean读取器,然后设置一些属性值。
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// 创建Xml格式的Bean读取器,里面会设置bean工厂的资源加载器及环境信息
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// 对象创建bean读取器的时候已经初始化.此处直接获取
beanDefinitionReader.setEnvironment(this.getEnvironment());
// 上述创建时已经初始化,此处直接获取
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
// 初始化beanDefinitionReader对象,此处设置配置文件是否要进行验证
initBeanDefinitionReader(beanDefinitionReader);
// 会解析xml中的标签属性,并添加到bean定义中.
loadBeanDefinitions(beanDefinitionReader);
}
然后接着往下看loadBeanDefinitions(beanDefinitionReader);
2.3loadBeanDefinitions(beanDefinitionReader)
这里会分为两个分支,一个是直接去解析resources,另外一个是去解析传入的配置文件列表,这里我们会走第二个分支。
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
// 通过另外一个构造函数构造的容器,会使用configResources的方式去加载bean定义
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
// 获取所有的配置文件名称,例如:{"beans.xml"}。主要是xml配置文件的名称
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
for (String location : locations) {
// 加载bean定义
count += loadBeanDefinitions(location);
}
return count;
}
@Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
2.4 loadBeanDefinitions(location,null)
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
// resourceLoader是在XmlApplicationContext中通过setResourceLoader方法设置进去的属性
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
// 加载bean定义.
int count = loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
}
return count;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
else {
// Can only load single resources by absolute URL.
Resource resource = resourceLoader.getResource(location);
int count = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
}
return count;
}
}
@Override
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int count = 0;
for (Resource resource : resources) {
// 加载bean定义
count += loadBeanDefinitions(resource);
}
return count;
}
其实到最后也是调用回到loadBeanDefinitions(resource);
2.5loadBeanDefinitions(resource)
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
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 == 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) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 执行bean定义加载
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();
}
}
}
这里真正干活的是doLoadBeanFinitions;
2.6 doLoadBeanDefinitions
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
// 将xml配置文件通过JDK中的JAXP(Java API for XMLProcessing)解析为Document对象
Document doc = doLoadDocument(inputSource, resource);
// 注册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);
}
}
2.7 registerBeanDefinitions
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
// 通过反射创建Bean定义文档读取器,默认类型为:DefaultBeanDefinitionDocumentReader
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
// 获取之前已经加载的bean定义数量,直接通过beanDefinitionMap.size获取
int countBefore = getRegistry().getBeanDefinitionCount();
// 执行xml的解析及bean定义注册。在创建bean定义读取器上下文时,会去创建默认的DefaultNamespaceHandlerResolver
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
// 返回本次注册的bean定义的数量
return getRegistry().getBeanDefinitionCount() - countBefore;
}
// 去解析注册bean定义
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
// 执行bean定义的注册操作
doRegisterBeanDefinitions(doc.getDocumentElement());
}
2.8 doRegisterBeanDefinitions
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.
BeanDefinitionParserDelegate parent = this.delegate;
// 创建bean定义解析器委托对象,同时解析<beans/>标签中的一些全局属性
this.delegate = createDelegate(getReaderContext(), root, parent);
if (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;
}
}
}
// 在spring解析xml之前,处理一些自定义的元素类型
preProcessXml(root);
// 解析bean定义
parseBeanDefinitions(root, this.delegate);
// 在spring解析xml之后,处理一些自定义的元素类型
postProcessXml(root);
this.delegate = parent;
}
preProcessXml和postProcessXml这两个进去你们可以看到是一个空实现,这里是可以留给我们进行拓展,这个是一个拓展点。
2.9 parseBeanDefinitions
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
// 判断是否为自定义标签,根据nameSpace的uri进行判断。
// spring的beans的nameSpace对应的uri为: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)) {
// 解析Spring中的默认xml节点(import,alias,beans)
parseDefaultElement(ele, delegate);
}
else {
// 解析自定义标签内容
delegate.parseCustomElement(ele);
}
}
}
}
else {
// 如果不是spring默认的命名空间,则作为扩展标签进行解析.
delegate.parseCustomElement(root);
}
}
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标签解析
doRegisterBeanDefinitions(ele);
}
}
这里就可以看到,如果是默认的标签:import、bean、beans、alias就会走默认的解析,parseDefaultElement,否则就走parseCustomElement。
三、自定义配置文件解析
3.1 User.java
public class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
3.2 自定义UserBeanDefinitionParse
/**
* @author maoqichuan
* @date 2022年02月21日 9:52
*/
public class UserNameBeanDefinitionParser implements BeanDefinitionParser {
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClass(User.class);
String id = element.getAttribute("id");
String userName = element.getAttribute("userName");
// 此处可以加一些自定义的校验逻辑,校验必填属性的值及类型或者格式等
if (null == id || "".equals(id.trim())) {
throw new RuntimeException("id不能为空!");
}
// 注册bean定义到bean定义注册中心
parserContext.getRegistry().registerBeanDefinition(id, beanDefinition);
if (StringUtils.hasText(id)) {
beanDefinition.getPropertyValues().addPropertyValue("id", id);
}
if (StringUtils.hasText(userName)) {
beanDefinition.getPropertyValues().addPropertyValue("name", userName);
}
return beanDefinition;
}
}
3.3 UserNamespaceHandler
/**
* MyNamespaceHandler
*/
public class UserNamespaceHandler extends NamespaceHandlerSupport{
/**
* 注册标签的解析类
*/
@Override
public void init() {
registerBeanDefinitionParser("mqc:user",new UserBeanDefinitionParse());
}
}
3.4 创建Spring.handlers文件
在resource目录下创建META-INF目录下,并创建三个文件:Spring.handlers,Spring.schemas、user.xsd。
Spring.handlers:
http\://www.mqc.com/schema/user=org.springframework.mqc.selftag.UserNamespaceHandler
Spring.schemas:
http\://www.mqc.com/schema/user.xsd=META-INF/user.xsd
user.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.mqc.com/schema/user"
xmlns:tns="http://www.mqc.com/schema/user"
elementFormDefault="qualified">
<element name="mqc">
<complexType>
<attribute name ="userName" type = "string"/>
</complexType>
</element>
</schema>
3.5创建配置文件
<?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:aaa="http://www.mqc.com/schema/user"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.mqc.com/schema/user http://www.mqc.com/schema/user.xsd">
<aaa:mqc userName = "lee" />
</beans>
到这里spring自定义标签大概就已经结束了,其实如果到后面的公司有自定义标签的需求的话,大家可以去看看spring context的标签解析,spring怎么做我们就怎么做就可以了。