IOC容器分类(核心数据结构BeanDefinition)
- BeanFactory基础实现
- ApplicationContext高级实现
启动过程分析
IOC容器启动:包括BeanDefinition的Resource的定位、载入、注册三个过程。spring将其分开,通过不同模块来完成,以便用户可以对三个过程进行剪裁或扩展
- 定位:ResourceLoader 如:FileSystemResource(读取文件系统中resource
)、ClassPathResource(读取classPath中resource)、servletContextResource - 载入:BeanDefinitionReader
- 注册:BeanDefinitionRegistry
初始化完成的BeanDefinition保存在ConcurrentHashMap中
BeanFactory 和 FactoryBean &来区分
- beanFactory是factory spring中的bean都由它管理
- 一个是bean 特殊的bean 能产生或者修饰对象生成的工厂bean (工厂模式 修饰器模式)
基础IOC容器分析:BeanFactory
- DefaultListablesBeanFactory spring将其当成一个默认的功能完整的IOC容器使用
- XmlBeanDefinitionReader 解析xml方式配置的BeanDefinition
使用方法loadBeanDefinitions(Resource resource)
编程方式分析IOC
- 创建IOC配置文件抽象资源,资源包含了BeanDefinitions定义
- 创建一个BeanFactory,一般使用DefaultListablesBeanFactory
- 创建一个BeanDefinition读取器,XmlBeanDefinitionReader
载入XML形式的BeanDefinition - 读取配置信息
- IOC容器建立,使用
示例代码
package com.chenfei;
import com.chenfei.entity.Teacker;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
/**
* Created by chenfei on 2017/7/31.
*/
public class SpringCode {
public static void main(String[] args) {
ClassPathResource resource = new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory );
reader.loadBeanDefinitions(resource);
Teacker teacker = (Teacker)factory.getBean("teacher");
teacker.teach();
}
}
高级IOC容器分析:ApplicationContext
除了支持基本IOC容器功能,增加了- 支持不同的信息源
- 访问资源(可以从不同的途径得到Bean定义的资源) 继承DefaultResourceLoader
- 支持应用事件 实现接口ApplicationEventPublisher
- 一般建议使用applicationContext作为IOC容器的基本形式
已FileSystemXmlApplicationContext来分析ApplicationContext , 类图如下
FileSystemXmlApplicationContext 构造方法
设置configLocation
调用父类AbstractApplicationContext中refresh初始化容器
AbstractApplicationContext refresh()方法
- 调用子类AbstractRefreshableApplicationContext中 refreshBeanFactory()
创建IOC容器DefaultListableBeanFactory,启动载入BeanDefinition
AbstractRefreshableApplicationContext refreshBeanFactory()方法
- 调用子类AbstractXmlApplicationContext中loadbeanDefinitions()方法 创建
XmlbeanDefinitionReader
设置ResourceLoader
启动载入BeanDefinition(AbstractBeanDefinitionReader实现方法loadBeanDefinitions())
AbstractBeanDefinitionReader
- 调用子类XmlBeanDefinitionReader loadBeanDefinitions() 方法
XmlBeanDefinitionReader
- loadBeanDefinitions(resource) 方法
- doLoadBeanDefinitions(InputSource ,resource)方法(1)
- registerBeanDefinitions(Document,Resource)方法
创建DefaultBeanDefinitionDocumentReader 调用其 - registerBeanDefinitions(Document,XmlReaderContext)方法
DefaultBeanDefinitionDocumentReader
- registerBeanDefinitions(Document,XmlReaderContext)方法
- doRegisterbeanDefinitions(Element)
创建BeanDefinitionParserDelegate - parseBeanDefinitions(Element,BeanDefinitionParserDelegate)(2)
- parseDefaultElement(Element,BeanDefinitionParserDelegate)
- processBeanDefinition(Element,BeanDefinitionParserDelegate)
BeanDefinitionParserDelegate的parserBeanDefinitionElement(Element)方法
- 解析结果组装为BeanDefinitionHolder对象 ,该对象拥有BeanDefinition属性
BeanDefinitionReaderUtils
- RegisterBeanDefinition(BeanDefinitionHolder,BeanDefinitionRegistry)方法
将BeanDefinition注册到容器DefaultListableBeanFactory的map中
注意:
BeanDefinition载入分两部分
(1)调用Xml解析器得到document对象
(2)按照spring规则解析
BeanDefinition注册
isAllowBeanDefinitionOverriding有同名时判断,不允许抛出异常
源码分析
AbstractApplicationContext中实现refresh
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
//创建beanFactory 在子类中启动refreshBeanFactory()
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
//设置beanFactory后置处理
this.postProcessBeanFactory(beanFactory);
//调用beanFactory后处理器,这些后处理器是在bean定义中向容器注册的
this.invokeBeanFactoryPostProcessors(beanFactory);
//注册bean的后处理器,在bean创建过程中调用
this.registerBeanPostProcessors(beanFactory);
//对上下文中的消息源进行初始化
this.initMessageSource();
//初始化上下文中的事件机制
this.initApplicationEventMulticaster();
//初始化其它特殊bean
this.onRefresh();
//检查监听bean,并将这些bean向容器注册
this.registerListeners();
//实例化所有的(non-lazy-init)
this.finishBeanFactoryInitialization(beanFactory);
//发布容器事件,结束refresh过程
this.finishRefresh();
} catch (BeansException var9) {
if(this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
应用于文件系统的Resource实现, 该方法在BeanDefinitionReader中loadBeanDefinition()中被调用 (loadBeanDefinition 才有模版模式,具体实现由子类实现)
protected Resource getResourceByPath(String path) {
if(path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
AbstractRefreshableApplicationContext
protected final void refreshBeanFactory() throws BeansException {
if(this.hasBeanFactory()) {
this.destroyBeans();
this.closeBeanFactory();
}
try {
//创建IOC容器 这里使用DefaultListableBeanFactory
DefaultListableBeanFactory ex = this.createBeanFactory();
ex.setSerializationId(this.getId());
this.customizeBeanFactory(ex);
//启动对BeanDefinition的载入
this.loadBeanDefinitions(ex);
Object var2 = this.beanFactoryMonitor;
synchronized(this.beanFactoryMonitor) {
this.beanFactory = ex;
}
} catch (IOException var5) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
}
}
AbstractXmlApplicationContext
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
//创建BeanDefinitionReader,通过回调设置到beanFactory中
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
beanDefinitionReader.setEnvironment(this.getEnvironment());
//配置ResourceLoader,因为父类是DefaultResourceLoader,所有this直接使用
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
//启动bean信息定义载入过程
this.initBeanDefinitionReader(beanDefinitionReader);
this.loadBeanDefinitions(beanDefinitionReader);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = this.getConfigResources();
if(configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = this.getConfigLocations();
if(configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
AbstractBeanDefinitionReader
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
//这里获取的是DefaultResourceLoader
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
int loadCount = loadBeanDefinitions(resources);
if (actualResources != null) {
for (Resource resource : resources) {
actualResources.add(resource);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
}
return loadCount;
}
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 loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}
DefaultResourceLoader
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
Iterator ex = this.protocolResolvers.iterator();
Resource resource;
do {
if(!ex.hasNext()) {
//处理'/'开头的Resource
if(location.startsWith("/")) {
return this.getResourceByPath(location);
}
//处理 classpath开头 的Resource
if(location.startsWith("classpath:")) {
return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());
}
try {
//处理URL标识的Resource
URL ex1 = new URL(location);
return new UrlResource(ex1);
} catch (MalformedURLException var5) {
//其它情况 默认得到ClassPathContextReaource 一般由子类实现见AbstractApplicationContext中实现
return this.getResourceByPath(location);
}
}
ProtocolResolver protocolResolver = (ProtocolResolver)ex.next();
resource = protocolResolver.resolve(location, this);
} while(resource == null);
return resource;
}
XmlBeanDefinitionReader
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.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(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 {
//调用xml解析器得到Document对象
Document doc = doLoadDocument(inputSource, resource);
//使用spring规则解析document 并调用BeanDefinitionReaderUtils注册BeanDefinition
return registerBeanDefinitions(doc, resource);
}
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);
}
}
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//创建BeanDefinitionDocumentReader
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//使用 documentReader 按spring规则解析document
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
DefaultBeanDefinitionDocumentReader
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
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);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isInfoEnabled()) {
logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
preProcessXml(root);
//使用BeanDefinitionParserDelegate 解析
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
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 (node instanceof 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);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
doRegisterBeanDefinitions(ele);
}
}
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
//注册beanDefinition到容器 DefaultListableBeanFactory
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}