(一)spring如何从xml文件加载java对象
先介绍spring加载xml的关键类以及接口
XmlBeanDefinitionReader
该类主要用于从xml文件中读取bean对象的一些定义例如,xml中设置的属性信息,构造函数信息等等
继承关系如下图
注释:BeanDefinitionReader:该类属于spring用于读取bean信息的抽象接口
并且采用模板设计模式实现bean信息的加载 基本操作有AbstractBeanDefinitionReader类实现,
EnvironmentCapable:根据翻译是改接口具有获取spring环境的能力
其中的环境指操作系统设置的环境以及通过配置文件配置的环境
例如System.setProperty(“key”,“value”)
BeanDefinitionDocumentReader
实际上被XmlBeandefinitionReader用于解析Dom文档的,该接口没有父接口。
ClassPathXmlApplicationContext
spring中 独立的xml应用上下文,从 类路径中获取获取上下文定义文件,
并且将普通路径解析为包路径的资源名称,对于测试工具以及jar中嵌入的应用程序上下文非常有用,配置位置默认值可以通过 **AbstractRefreshableConfigApplicationContext#getConfigLocations()**方法覆盖,配置位置可以表示为具体的文件,如“/myfiles”/context.xml"
或者像“/myfiles/*-context.xml,在多个配置路径情况下,后面的bean 定义信息将覆盖在更早加载的文件中定义信息,这可以用来通过一个额外的XML文件故意覆盖某些bean定义这可以用来通过一个额外的XML文件故意覆盖某些bean定义。
类图如下

加载过程
流程图如下
1.初始化ClasspathXmlApplicationContext,需要一个String的构造参数即配置文件地址,设置配置路径如果不设置就是用默认的(resource:public/template等等)
2.然后调用refresh()方法,为了线程安全使用了同步锁,以Object startupShutdownMonitor 对象为锁的key,调用 ***AbstractApplicationContext#obtainBeanFactory()*方法刷新 bean factory,其中 的refreshBeanFactory()已经被AbstractRefreshableApplicationContext类实现,
并且ClassPathXmlApplicationContext 继承 AbstractRefreshableApplicationContext
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
其中 DefaultListableBeanFactory beanFactory = createBeanFactory(); 是创建
beanFactory,代码如下
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
是的,spring创建bean工厂就是这么简单没我们想的那么复杂,spring的精髓在于思维,以及对设计模式的巧妙运用,看源码的时候不要束缚我们的思想要勇于猜想然后验证。废话先到这,进入正题。
下面是设置beanFactory的序列化ID再然后设置beanFactory,接下来是调用AbstractXmlApplicationContex#loadBeanDefinitionst方法加载BeanDefinition,代码如下
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
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.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
注意最后两行代码,spring告诉我们,我们可以扩展AbstractBeanDefinitionReader,
自定义BeandefitionReader去解析xml配置文件。下面的**loadBeanDefinitions()方法不是递归调用,上面代码块中的loadBeanDefinitions()**方法是实现
**AbstractRefreshableApplicationContext#loadBeanDefinitions()抽象方法,
而最后一行的loadBeanDefinitions(beanDefinitionReader);**方法是
AbstractXmlApplicationContex抽象类中的一个普通方法,代码如下
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
注意最后一个判断**(因为使用这个条件调试的)** ,这里调用的是
AbstractBeandefitionReader#loadBeanDefinitions(),这个是BeanDefitionReader的是实现类,(该类也是模板设计模式
BeanDefitionReader—AbstractBeanDefinitionReader
—XmlBeanDefinitionReader),然后再调用AbstractBeanDefitionReader自定义的
loadBeanDefinitions方法 ,代码如下
@Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
下面是AbstractBeanDefitionReader自定义的loadBeanDefinitions()方法
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
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);
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;
}
}
注意这行代码 int count = loadBeanDefinitions(resources);,该方法是
XmlBeanDefitionReader #int loadBeanDefinitions(Resource resource)
代码如下
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
XmlBeanDefitionReader自定义的
/**
* 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
*/
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!");
}
try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
注意
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());,该方法是真正加载Xml配置文件。
**XmlBeanDefitionReader#int doLoadBeanDefinitions(InputSource inputSource, Resource resource)**的代码块如下
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument(inputSource, resource);
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);
}
}
注意 int count = registerBeanDefinitions(doc, resource);这个是开始调用准备注册beanDefition的方法,代码块如下
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
注意 documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
代码块如下,doRegisterBeanDefinitions(doc.getDocumentElement());这个是这开始注册beanDefition
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
doRegisterBeanDefinitions(doc.getDocumentElement());
}
DefaultBeanDefinitionDocumentReader#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;
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;
}
}
}
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
本文详细介绍了Spring如何从XML文件加载Java对象,关键类包括XmlBeanDefinitionReader、BeanDefinitionDocumentReader和ClassPathXmlApplicationContext。加载过程涉及构造ClassPathXmlApplicationContext,调用refresh()方法,通过AbstractApplicationContext创建和刷新bean factory,然后加载BeanDefinition。整个过程通过模板设计模式实现,允许自定义BeanDefinitionReader来解析XML配置文件。

575

被折叠的 条评论
为什么被折叠?



