1.什么是IOC?
在面向对象系统中,对象封装了数据和对数据的处理,而对象之间的依赖关系体现在对数据和方法的依赖上。当业务
很复杂,涉及到的类非常多,这个时候如果由开发者手动的去给每个对象导入它依赖的对象,这将会导致代码高度耦
合,简直是牵一发而动全身。但如果,对象之间的依赖关系并不需要我们手动导入,而是将其交给某一个框架或者平
台来处理。这无疑会大大减少代码的耦合度,降低编码的复杂度,将应用从复杂的依赖关系中解放出来。
IOC(Inverse of Control)控制反转,有时候也被称为DI依赖注入,它是降低对象耦合关系的一种设计思想。根据
这个思想实现的Spring IOC容器反转了一个对象获取它所依赖对象的引用,对象之间的相互依赖都由IOC容器来进行
管理。
2.BeanFactory和ApplicationContext
Spring Ioc容器一般都是指二个,BeanFactory和ApplicationContext。BeanFactory是最顶层的接口,提供了
Ioc最基本的功能,而ApplicationContext是实现了BeanFactory,是一个高级Ioc容器。ApplicationContext提
供了AOP、WEB,国际化、事件监听、加载资源文件的能力等。
3.Ioc容器的初始化过程
3.1 基于XML文件的初始化
Ioc容器的启动分为三个过程:
- Resource定位过程;
- BeanDefinition的载入;
- 向Ioc容器注册BeanDefinition。
3.1.1初始化
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
applicationContext.xml资源文件:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="data" class="ttt.spring.bean.Data"></bean>
</beans>
ClassPathXmlApplicationContext类的继承关系:
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
//1.这时parent==null,一直调用父类构造函数,在AbstractApplicationContext设置父容器
super(parent);
//2.在AbstractRefreshableConfigApplicationContext中设置资源路径
setConfigLocations(configLocations);
if (refresh) {
//3.启动Ioc容器,是载入BeanDefinition的入口
refresh();
}
}
从上面源码可以看出,实例化ClassPathXmlApplicationContext其实也是做了三件事:
1. 为当前容器设置父容器;
2. 设置资源路径;
3. 启动Ioc容器。
3.1.2设置父容器
一直调用父类构造函数,调用路径如下:
AbstractXmlApplicationContext-》AbstractRefreshableConfigApplicationContext-》AbstractRefreshableApplicationContext-》AbstractRefreshableApplicationContext-》
AbstractApplicationContext。
public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
public AbstractRefreshableConfigApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
public AbstractRefreshableApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
setParent(parent);
}
AbstractApplicationContext调用自己的无参构造函数,并设置父容器:
//1.初始化资源路径解析器
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
//2.由于AbstractApplicationContext继承了DefaultResourceLoader,所以其也是一个ResourceLoader
protected ResourcePatternResolver getResourcePatternResolver() {
return new PathMatchingResourcePatternResolver(this);
}
//3.设置父容器
public void setParent(@Nullable ApplicationContext parent) {
//这时parent为null
this.parent = parent;
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
3.1.3设置资源路径
将解析到的路径加入到configLocations中:
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
//解析路径
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
//解析给定路径,并替换占位符如:$ {}
protected String resolvePath(String path) {
return getEnvironment().resolveRequiredPlaceholders(path);
}
3.2 refresh刷新容器
知道了资源路径,那接下来就是解析XML文件,将其变成可用的对象。
public void refresh() throws BeansException, IllegalStateException {
//加锁,防止在启动容器的过程中其他线程来操作
synchronized (this.startupShutdownMonitor) {
// 1.为Ioc容器的启动设置了启动时间、激活标志和初始化属性源
prepareRefresh();
// 2.解析配置文件生成BeanDefinition对象
//把beanName和对应的BeanDefinition存入容器中(还有别名)
//这一步并没有实例化bean对象
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
3.2.1 载入
先说说什么是BeanDefinition吧,Ioc容器把用户定义好的Bean表示成Ioc容器内部的数据结构,而这个结构就
是BeanDefinition。XML文件解析成可用的对象其实是分为二个步骤的:1.载入,2.依赖注入。Ioc容器内部会
将BeanDefinition注入到一个叫做beanDefinitionMap的ConcurrentHashMap中。Ioc容器的初始化一般不包括
依赖注入。
/**
* AbstractApplicationContext#obtainFreshBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//1.具体的实现是由AbstractApplicationContext的子类AbstractRefreshableApplicationContext
//实现的(委派模式)
refreshBeanFactory();
//2.获取子类创建的内部BeanFactory
return getBeanFactory();
}
obtainFreshBeanFactory()方法其实就是让子类AbstractRefreshableApplicationContext创建内部BeanFactory,这个内部BeanFactory其实就是DefaultListableBeanFactory,它真正的存储了BeanDefinition。然后再从子类AbstractRefreshableApplicationContext中获取这个BeanFactory,也就能够拿到整个的beanDefinitionMap了。
protected final void refreshBeanFactory() throws BeansException {
//1.如果已经有容器存在,则销毁容器并关闭容器
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//2.创建Ioc容器,创建的是DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
//3.给Ioc容器添加一些特性:是否允许bean重写和是否允许循环引用
customizeBeanFactory(beanFactory);
//4.启动对BeanDefinition的载入,具体实现由AbstractXmlApplicationContext来实现的
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
customizeBeanFactory主要就是否允许bean重写和是否允许循环引用:
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}
AbstractXmlApplicationContext具体实现加载beanDefinition到BeanFactory中:
/**
* Loads the bean definitions via an XmlBeanDefinitionReader.
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see #initBeanDefinitionReader
* @see #loadBeanDefinitions
*/
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// 创建XmlBeanDefinitionReader对象,是bean的读取器,它持有BeanFactory的引用
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//设置环境等属性
beanDefinitionReader.setEnvironment(this.getEnvironment());
//设置资源加载器
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
//当Bean读取器读取Bean定义的xml资源文件时,启用Xml的校验机制
initBeanDefinitionReader(beanDefinitionReader);
//这里是真正加载BeanDefinition的地方
loadBeanDefinitions(beanDefinitionReader);
}
AbstractXmlApplicationContext中的loadBeanDefinitions 方法:
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
//getConfigResources 直接获取配置的资源
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
//获取配置的路径,配置路径的文件最后会被读取为Resource
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
上面已经拿到了上面我们已经拿到了XmlBeanDefinitionReader,又知道了资源路径,可以开始加载资源了。跟进loadBeanDefinitions(configLocations)方法,方法是在AbstractBeanDefinitionReader中实现的:
//AbstractBeanDefinitionReader
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
for (String location : locations) {
count += loadBeanDefinitions(location);
}
return count;
}
//AbstractBeanDefinitionReader中的重载方法
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
/**
* AbstractBeanDefinitionReader#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);
//从这里可以看出,最终还是走的是加载Resource
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;
}
}
读取资源路径的文件生成Resource后,还是在XmlBeanDefinitionReader中继续加载BeanDefinition:
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
//从指定的xml文件中读取内容转换为BeanDefinition对象
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();
}
}
}
XmlBeanDefinitionReader的doLoadBeanDefinitions方法:
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//将xml转换为Document对象
Document doc = doLoadDocument(inputSource, resource);
//这里是重点,具体的解析由DocumentLoader实现
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);
}
}
registerBeanDefinitions方法
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//1.创建一个解析对象documentReader
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
//2.获取已经注册的BeanDefinition对象
int countBefore = getRegistry().getBeanDefinitionCount();
//3.解析的核心,具体根据xml定义的标签开始解析
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
//返回当前注册的bean的数量
return getRegistry().getBeanDefinitionCount() - countBefore;
}
真正的解析xml文件是在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;
}
将XML文件定义的标签按Spring语法解析成BeanDefinition是很复杂和繁琐的,这一段详细解析直接跳过。
3 总结
追了这么一大段,其实总结起来很简单:spring读取XML文件生成Resource对象,按照spring中第一XML元素标签进行解析成BeanDefinition,然后注册到BeanFactory中。
其实完成了BeanDefinition的注册,就是完成了Ioc容器的初始化,但是还没有完成依赖注入。这个时候Ioc容器DefaultListableBeanFactory中已经建立了整个Bean的配置信息,这些BeanDefinition已经可以被容器使用了,它们都被存储在beanDefinitionMap中被检索和使用。