1.beans核心类
1.DefaultListableBeanFactory xmlBeanFactory
xmlBeanFactory继承自DefaultListableBeanFactory,DefaultListableBeanFactory是整个bean加载的核心,是spring注册与加载bean的默认实现,
而对于XmlBeanFactory与DefaultListableBeanFactory不同在于XmlBeanFactory有自定义的xml读取器xmlBeanDefinitionReader。实现了个性化的BeanDefinitionReader
在XmlBeanFactory中主要使用reader属性对资源文件进行读取和注册。
2.XmlBeanDefinitonReader
xml配置文件的读取
3.xmlBeanFactory
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
1.创建xmlBeanFactory
a)public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader.loadBeanDefinitions(resource);
}
b)public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
c)public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
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();
}
}
d) protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
//获取对xml文件的验证模式
int validationMode = getValidationModeForResource(resource);
//加载xml文件,并得到对应的Documnet
Document doc = this.documentLoader.loadDocument(
inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);
//根据返回的Documnet注册Bean信息
return registerBeanDefinitions(doc, resource);
}
d1) private int getValidationModeForResource(Resource resource) {
return (this.validationMode != VALIDATION_AUTO ? this.validationMode : detectValidationMode(resource));
}
d2)InputStream inputStream;
inputStream = resource.getInputStream();
return this.validationModeDetector.detectValidationMode(inputStream);
d3)public int detectValidationMode(InputStream inputStream) throws IOException {
// Peek into the file to look for DOCTYPE.
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
boolean isDtdValidated = false;
String content;
while ((content = reader.readLine()) != null) {
content = consumeCommentTokens(content);
if (inComment || !StringUtils.hasText(content)) {
continue;
}
// private boolean hasDoctype(String content) {
//return content.indexOf(DOCTYPE) > -1;
//}
if (hasDoctype(content)) {
isDtdValidated = true;
break;
}
else if (hasOpeningTag(content)) {
// End of meaningful data
break;
}
}
return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD);
}
finally {
reader.close();
}
}
2.DTD与XSD区别
DTD是xml文件的验证机制,属于xml文件的一部分。
XSD本身是xml文档,可以用指定的XSD来验证某个xml文档
EntityResolver: