首先写一个测试用例,用XmlBeanFactory来实例化BeanFactory。
1.jpg首先看下XmlBeanFactory的结构:
2.jpg从图中可以看出XmlBeanFactory继承了DefaultListableBeanFactory,组合了XmlBeanDefinitionReader从名字中我们可以看出这是一个用于解析XML配置文件的类。XmlBeanFactory有俩个构造方法,最下面一个方法我们可以factory通过reader来加载BeanDefinition(spring中每一个POJO对应一个BeanDefinition)
通过上面我们可以看到spring是通过XmlBeanDefinitionReader来解析xml加载BeanDefinition,下面我们来通过查看XmlBeanDefinitionReader的部分代码来了解其具体的加载过程。
public int loadBeanDefinitions(Resource resource)throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
public int loadBeanDefinitions(EncodedResource encodedResource)throws BeanDefinitionStoreException {
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());//设置编码
}
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();
}
}
}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);//解析xml模式,
Document doc =this.documentLoader.loadDocument(
inputSource, getEntityResolver(),this.errorHandler, validationMode, isNamespaceAware());
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
。。。。。部分异常处理省去
}
public int registerBeanDefinitions(Document doc, Resource resource)throws BeanDefinitionStoreException {
// Read document based on new BeanDefinitionDocumentReader SPI.
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();//BeanDefinitionDocumentReader是一个接口类,通过createBeanDefinitionDocumentReader我们可以知道具体的BeanDefinitionDocumentReader类为DefaultBeanDefinitionDocumentReader
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));//通过DefaultBeanDefinitionDocumentReader类来解析
return getRegistry().getBeanDefinitionCount() - countBefore;
}
protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
}
下面通过查看DefaultBeanDefinitionDocumentReader来查看注册BeanDefinition过程。
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
preProcessXml(root);
parseBeanDefinitions(root, delegate);//具体的解析
postProcessXml(root);
}
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 (nodeinstanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele);
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele,IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele,ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele,BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);//解析bean
}
}
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder !=null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());//注册BeanDefinition
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() +"'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());//调用registry的registerBeanDefinition方法,通过分析可以知道其实调用的是DefaultListableBeanFactory的registerBeanDefinition。DefaultListableBeanFactory实现了BeanDefinitionRegistry接口
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases !=null) {
for (String aliase : aliases) {
registry.registerAlias(beanName, aliase);
}
}
}
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {
Assert.hasText(beanName,"Bean name must not be empty");
Assert.notNull(beanDefinition,"BeanDefinition must not be null");
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
synchronized (this.beanDefinitionMap) {
Object oldBeanDefinition =this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition !=null) {
if (!this.allowBeanDefinitionOverriding) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition +"] for bean '" + beanName +
"': There is already [" + oldBeanDefinition +"] bound.");
}
else {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"': replacing [" + oldBeanDefinition +"] with [" + beanDefinition +"]");
}
}
}
else {
this.beanDefinitionNames.add(beanName);
this.frozenBeanDefinitionNames =null;
}
this.beanDefinitionMap.put(beanName, beanDefinition);
resetBeanDefinition(beanName);
}
}
网友评论