高级JAVA开发 Spring部分(Context源码解析)
参考和摘自:
《spring源码深度解析(第2版)》 郝佳
Spring Bean的生命周期 —附详细流程图及测试代码
源码分析:doCreateBean
有错误,请无情拍砖!~
我的邮箱:guosheng.tan@foxmail.com
注释源码Git:https://github.com/tanguosheng/spring-framework
下载源码看更舒服些~
Spring容器源码解析
基于spring 5.0.x版本。
spring-context包提供了多种context以供使用,常见的例如:AnnotationConfigApplicationContext、ClassPathXmlApplicationContext等。ClassPathXmlApplicationContext是最基础的Context构建方式,从它入手即可了解spring的工作原理。先贴一张类继承图:
spring框架设计非常巧妙,继承与调用关系错综复杂,提前了解继承关系以便分析代码找到正确实现类,以下分析思路仅关注脉络。
spring上下文基础用法即:
new ClassPathXmlApplicationContext("applicationContext.xml").getBean("beanName");
看看new ClassPathXmlApplicationContext("applicationContext.xml")
都做了啥:
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
// 把当前的父context设置进去,这里是null
super(parent);
// 将外面塞进来的配置文件路径设置进去,等待一会儿解析。
setConfigLocations(configLocations);
if (refresh) { // true
// 刷新。加载从这里开始
refresh();
}
}
继续探究refresh方法:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 1. 初始化前的准备工作,例如对系统属性或者环境变量进行准备及验证。
// 可以重写其中的方法达到提前验证某些变量是否存在的目的
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 2. 初始化BeanFactory,并进行XML文件读取。
// 在这里验证解析xml文件、注册bean到容器中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 3. 对BeanFactory进行各种功能填充。比如:
// 设置classLoader、增加#{bean.xxx}表达式语言的支持、增加默认propertyEditor工具、
// 设置忽略自动装配的接口、增加AspectJ的支持、增加几个默认系统环境bean
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 4.子类覆盖方法做额外处理。(框架设计,这里是空方法)
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 5. 激活注册的BeanFactoryPostProcessor处理器。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 6. 注册拦截bean创建的bean处理器,这里只是注册,真正的调用是在getBean时候。
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 7. 为上下文初始化Message源,即对不同语言的消息体进行国际化处理。
initMessageSource();
// Initialize event multicaster for this context.
// 8. 初始化应用消息广播器,并放入“applicationEventMulticaster”bean中。
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 9. 留给子类来初始化其他的bean。
onRefresh();
// Check for listener beans and register them.
// 10.在所有注册的bean中查找listener bean,注册到消息广播器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 11. 实例化剩下的单实例(非惰性的)。
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 12. 完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,
// 同时发出ContextRefreshEvent通知别人。
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.
// 销毁已经创建的单例bean
destroyBeans();
// Reset 'active' flag.
// 重置active标签
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...
// 重置Spring核心中的缓存
resetCommonCaches();
}
}
}
比较关心的步骤一一解读:
步骤2:初始化BeanFactory、XML文件读取。
// AbstractApplicationContext.java:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新BeanFactory
refreshBeanFactory();
// 初始化BeanFactory,然后返回beanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName()
+ ": " + beanFactory);
}
return beanFactory;
}
// AbstractRefreshableApplicationContext.java: refreshBeanFactory 方法
@Override
protected final void refreshBeanFactory() throws BeansException {
// 如果已经存在BeanFactory,销毁已经生成好的bean并且关闭BeanFactory
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
// 创建BeanFactory(DefaultListableBeanFactory),标注为 ①,下文贴代码可以看到
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 设置BeanFactory的序列化ID
beanFactory.setSerializationId(getId());
// 在customizeBeanFactory方法中设置两个布尔参数:
// allowBeanDefinitionOverriding、allowCircularReferences
// 标注为 ② ,下文分析
customizeBeanFactory(beanFactory);
// 正式开始解析xml,标注为 ③
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
// BeanFactory作为成员变量被AbstractRefreshableApplicationContext类持有。
this.beanFactory = beanFactory;
}
} catch (IOException ex) {
throw new ApplicationContextException(
"I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
BeanFactory作为成员变量被AbstractRefreshableApplicationContext类持有。
① 深入createBeanFactory方法:
protected DefaultListableBeanFactory createBeanFactory() {
// 可以看到创建的BeanFactory类型是DefaultListableBeanFactory
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
// new DefaultListableBeanFactory时把父BeanFactory传进来并保存
public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
// 调用父类(AbstractAutowireCapableBeanFactory)构造
super(parentBeanFactory);
}
public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
// 调用本地构造
this();
// 保存父BeanFactory
setParentBeanFactory(parentBeanFactory);
}
public AbstractAutowireCapableBeanFactory() {
// 继续调用父类(AbstractBeanFactory)构造,这个构造是空的
super();
// 忽略三个接口依赖:BeanNameAware、BeanFactoryAware、BeanClassLoaderAware
// 这里记录下来三个类的class,
// 在后面的bean自动装载时(byName、byType)会自动忽略装载三个接口实现类的属性
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
贴上一张DefaultListableBeanFactory的继承图,DefaultListableBeanFactory对象承担了BeanFactory、BeanRegistry、AliasRegistry角色,在后续代码中在不同场景下把它转成各种接口类型来承担各种角色,其实都是它自己…
② 深入customizeBeanFactory方法:
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
if (this.allowBeanDefinitionOverriding != null) {
// allowBeanDefinitionOverriding:允许同名BeanDefinition覆盖,
// 用applicationContext.setAllowBeanDefinitionOverriding(true);来设置
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.allowCircularReferences != null) {
// allowCircularReferences:单例bean是否禁用循环依赖检测
// 用applicationContext.setAllowCircularReferences(false); 来设置禁止,
// 设置后有循环依赖会提前抛异常;
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}
③ loadBeanDefinitions方法正式开始解析xml,继续深入分析:
// AbstractXmlApplicationContext.java:
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 用给定的 beanFactory(DefaultListableBeanFactory类型)
// 创建一个新的 XmlBeanDefinitionReader,单一职责,用Reader去解析文件
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);
// 加载BeanDefinitions,主要逻辑在这里边,看下面代码
loadBeanDefinitions(beanDefinitionReader);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader)
throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
// loadBeanDefinitions方法的重载,把参数转化成EncodedResource类型后解析
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
// loadBeanDefinitions方法的重载,把参数转化成EncodedResource类型后解析
reader.loadBeanDefinitions(configLocations);
}
}
以上两处红框代码最终都会调用到:
XmlBeanDefinitionReader.java 中的loadBeanDefinitions(EncodedResource encodedResource)
方法。
解析及注册BeanDefinition
以下分析的代码是spring-beans、spring-core包下的代码。spring-beans、spring-core包提供解析bean的基础功能:读取文件、解析文件生成BeanDefinition对象、装载对象等。
记录已加载过的资源,inputStream封装成inputSource,进入解析部分,继续深入doLoadBeanDefinitions方法。
// XmlBeanDefinitionReader.java:
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);
}
Set<EncodedResource> 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 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进行校验。校验成功后加载xml得到Document对象。
// xml的格式定义文件有两种DTD和XSD,
// 这里会根据xml头中的配置来取得校验模式、格式定义文件进行校验。不赘述,重点放到解析上。
Document doc = doLoadDocument(inputSource, resource);
// 对Document对象解析配置,其中有bean、beans、import、alias等标签,注册Bean信息。
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 {
// 方法内部用反射的方式实例化了DefaultBeanDefinitionDocumentReader
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
// 记录注册前BeanDefinition个数
int countBefore = getRegistry().getBeanDefinitionCount();
// 注册BeanDefinition,下文代码分析这个方法
// createReaderContext创建Reader上下文,查看是如何创建的
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
// 返回注册前后BeanDefinition个数差
return getRegistry().getBeanDefinitionCount() - countBefore;
}
// 创建Reader上下文,关注getNamespaceHandlerResolver()方法
public XmlReaderContext createReaderContext(Resource resource) {
return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
this.sourceExtractor, this, getNamespaceHandlerResolver());
}
public NamespaceHandlerResolver getNamespaceHandlerResolver() {
if (this.namespaceHandlerResolver == null) {
// 创建默认命名空间HandlerResolver,关注这个方法
this.namespaceHandlerResolver = createDefaultNamespaceHandlerResolver();
}
return this.namespaceHandlerResolver;
}
protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
ClassLoader cl = (getResourceLoader() != null ?
getResourceLoader().getClassLoader() : getBeanClassLoader());
// 关注new DefaultNamespaceHandlerResolver时初始化了什么
return new DefaultNamespaceHandlerResolver(cl);
}
// DefaultNamespaceHandlerResolver.java
public DefaultNamespaceHandlerResolver(@Nullable ClassLoader classLoader) {
/*
* DEFAULT_HANDLER_MAPPINGS_LOCATION = "META-INF/spring.handlers"
* 这个常量的注释是:
* The location to look for the mapping files. Can be present in multiple JAR files.
* 查找映射文件的位置。可以存在于多个JAR文件中。
*/
this(classLoader, DEFAULT_HANDLER_MAPPINGS_LOCATION);
}
public DefaultNamespaceHandlerResolver(
@Nullable ClassLoader classLoader, String handlerMappingsLocation) {
Assert.notNull(handlerMappingsLocation, "Handler mappings location must not be null");
// 设置classLoader
this.classLoader = (classLoader != null ?
classLoader : ClassUtils.getDefaultClassLoader());
// 设置handlerMappingsLocation = "META-INF/spring.handlers"
this.handlerMappingsLocation = handlerMappingsLocation;
}
"META-INF/spring.handlers"路径是spring配置自定义标签解析器留下的钩子,程序读取每个包下META-INF/spring.handlers文件,加载文件中配置的nameSpace和NamespaceHandler接口的直接或间接实现类,实现类中向容器中注册用户自己实现的BeanDefinitionParser接口的实现类来实现自定义标签的解析。和spring.handlers文件配套配置的还有spring.schemas文件,它定义命名空间和xml schema(xsd或dtd文件)之间的关系。
< dubbo:xxx >、< tx:xxx >等标签都是这样实现的。
以上关于handlerMappingsLocation = "META-INF/spring.handlers"的分析先告一段落,自定义标签解析时继续分析。
例子参考:基于Spring开发——自定义标签及其解析 感谢作者~~
registerBeanDefinitions()方法:
// DefaultBeanDefinitionDocumentReader.java:
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
// 读取root节点
Element root = doc.getDocumentElement();
// root节点扔进去解析并注册
doRegisterBeanDefinitions(root);
}
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;
/*
* 在createDelegate方法中创建了BeanDefinitionParserDelegate对象,初始化委托对象时顺带着解析了:
* default-lazy-init: 指定<beans>元素下配置的所有bean默认的延迟初始化行为
* default-merge: 指定<beans>元素下配置的所有bean默认的merge行为
* default-autowire: 指定<beans>元素下配置的所有bean默认的自动装配行为
* default-init-method: 指定<beans>元素下配置的所有bean默认的初始化方法
* default-destroy-method: 指定<beans>元素下配置的所有bean默认的回收方法
* default-autowire-candidates: 指定<beans>元素下配置的所有bean默认是否作为自动装配的候选Bean
*/
this.delegate = createDelegate(getReaderContext(), root, parent);
/*
* 如果是默认命名空间,解析profile属性。
* profile属性可以作为多套环境配置使用。
* 它可以理解为我们在Spring容器中所定义的Bean的逻辑组名称,
* 只有当这些Profile被激活的时候,才会将Profile中所对应的Bean注册到Spring容器中。
*/
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);
// 解析BeanDefinitions
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);
}
}
profile用法详解:详解Spring中的Profile 感谢作者~~
默认标签解析
// DefaultBeanDefinitionDocumentReader.java:
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
// 解析import标签,例如:<import resource="customerContext.xml"/>
importBeanDefinitionResource(ele);
} else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
// 解析alias标签
processAliasRegistration(ele);
} else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
// 解析bean标签
processBeanDefinition(ele, delegate);
} else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
// 解析beans标签,递归调用doRegisterBeanDefinitions
doRegisterBeanDefinitions(ele);
}
}
import标签解析:
例如:<import resource="customerContext.xml"/>
protected void importBeanDefinitionResource(Element ele) {
// 获取resource属性
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
// 解析系统属性,例如"${user.dir}"
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<>(4);
// Discover whether the location is an absolute or relative URI
// 判定location是绝对URI还是相对URI
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location)
|| ResourceUtils.toURI(location).isAbsolute();
} catch (URISyntaxException ex) {
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
}
// Absolute or relative?
if (absoluteLocation) {
// 绝对路径直接根据地址加载对应的配置文件
try {
// 递归调用bean的解析过程
int importCount = getReaderContext()
.getReader().loadBeanDefinitions(location, actualResources);
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount
+ " bean definitions from URL location [" + location + "]");
}
} catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]",
ele, ex);
}
} else {
// No URL -> considering resource location as relative to the current file.
// 相对地址则根据地址计算出绝对地址
try {
int importCount;
// Resource存在多个子实现类,如VfsResource、FileSystemResource等,
// 而每个resource的createRelative方式实现都不一样,
// 所以这里先使用子类的方法尝试解析
Resource relativeResource = getReaderContext()
.getResource().createRelative(location);
if (relativeResource.exists()) {
// 递归调用bean的解析过程
importCount = getReaderContext()
.getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
} else {
// 如果解析不成功,则使用默认的解析器ResourcePatternResolver进行解析
String baseLocation = getReaderContext()
.getResource().getURL().toString();
// 递归调用bean的解析过程
importCount = getReaderContext()
.getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location),
actualResources);
}
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount
+ " bean definitions from relative location ["
+ location + "]");
}
} catch (IOException ex) {
getReaderContext().error(
"Failed to resolve current resource location", ele, ex);
} catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from relative location ["
+ location + "]", ele, ex);
}
}
// 解析后进行监听器激活处理
Resource[] actResArray = actualResources.toArray(new Resource[0]);
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
alias标签:
声明方式例如:
<bean id="beanA" class="src.com.BeanA"/>
<alias name="beanA" alias="oneBean,twoBean"/>
还有其他种声明方式不一一列举。
protected void processAliasRegistration(Element ele) {
// alias标签的name属性值
String name = ele.getAttribute(NAME_ATTRIBUTE);
// alias标签的alias属性值
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
boolean valid = true;
if (!StringUtils.hasText(name)) {
getReaderContext().error("Name must not be empty", ele);
valid = false;
}
if (!StringUtils.hasText(alias)) {
getReaderContext().error("Alias must not be empty", ele);
valid = false;
}
if (valid) {
// name、alias都非空,用bean的name属性和alias注册
try {
// getReaderContext().getRegistry()取出来的就是前文的DefaultListableBeanFactory对象,
// 调用SimpleAliasRegistry.java中的registerAlias方法。
getReaderContext().getRegistry().registerAlias(name, alias);
} catch (Exception ex) {
getReaderContext().error("Failed to register alias '" + alias +
"' for bean with name '" + name + "'", ele, ex);
}
// 激活监听
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
}
// SimpleAliasRegistry.java registerAlias方法
@Override
public void registerAlias(String name, String alias) {
Assert.hasText(name, "'name' must not be empty");
Assert.hasText(alias, "'alias' must not be empty");
synchronized (this.aliasMap) {
if (alias.equals(name)) {
// 如果别名和name相同那么删除注册的别名
this.aliasMap.remove(alias);
if (logger.isDebugEnabled()) {
logger.debug(
"Alias definition '" + alias + "' ignored since it points to same name");
}
} else {
String registeredName = this.aliasMap.get(alias);
if (registeredName != null) {
if (registeredName.equals(name)) {
// An existing alias - no need to re-register
return;
}
// SimpleAliasRegistry.java 中的 allowAliasOverriding 方法永远返回true,
// 意思是允许别名覆盖,
// 这里可以用子类覆盖此方法,返回false不允许别名覆盖
if (!allowAliasOverriding()) {
throw new IllegalStateException(
"Cannot define alias '" + alias + "' for name '" + name
+ "': It is already registered for name '" + registeredName + "'.");
}
if (logger.isInfoEnabled()) {
logger.info("Overriding alias '" + alias
+ "' definition for registered name '" + registeredName
+ "' with new target name '" + name + "'");
}
}
// 检查别名是否有循环指向,比如aliasA -> aliasB -> aliasA,
// 如果存在循环指向的话在getBean时候就死循环啦 ~
checkForAliasCircle(name, alias);
// 校验通过,用ConcurrentHashMap类型的aliasMap保存alias和name的对应关系。
this.aliasMap.put(alias, name);
if (logger.isDebugEnabled()) {
logger.debug("Alias definition '"
+ alias + "' registered for name '" + name + "'");
}
}
}
}
beans标签:
对前文的doRegisterBeanDefinitions方法的递归调用。
bean标签:重点!!!(超级复杂啊~~~)
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
// ④
/*
* 委托BeanDefinitionParserDelegate进行元素解析,
* 返回的bdHolder持有GenericBeanDefinition对象,
* GenericBeanDefinition装着bean标签的class、name、id、aliases等属性值
* 下文详解此方法,把它标为 ④
*/
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
/*
* 对默认标签下的自定义标签进行解析,比如:
* <bean id="bean" class="test.Bean">
* <myTag:my value="this is value">
* </bean>
* 方法大概实现:遍历所有属性,发现需要修饰的属性时则获取对应标签的命名空间,
* 再找到对应的解析器对它进行解析,自定义标签如何解析在后文分析
*/
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
// ⑤
/* 注册BeanDefinition,也就是把BeanDefinition存到Map里,把bean的alias也存起来,
* 后文详细分析此方法,把它标为 ⑤
* 还记得在AbstractXmlApplicationContext.java 的 loadBeanDefinitions 方法中初始化的
* new XmlBeanDefinitionReader(beanFactory)吗?
* getReaderContext().getRegistry()取得的
* 就是这个 beanFactory -> DefaultListableBeanFactory,
* 它作为 Registry 的角色出现了
*/
BeanDefinitionReaderUtils.registerBeanDefinition(
bdHolder, getReaderContext().getRegistry());
} catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
// 发出响应事件,通知相关的监听器,这个bean已经加载完成了
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
④ parseBeanDefinitionElement 方法详细分析如下:
// BeanDefinitionParserDelegate.java 的 parseBeanDefinitionElement 方法
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(
Element ele, @Nullable BeanDefinition containingBean) {
// id 属性
String id = ele.getAttribute(ID_ATTRIBUTE);
// name属性
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
// 分割name属性视为alias
List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(
nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
// 移除和id相同的的alias
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
// 校验bean id的唯一性
checkNameUniqueness(beanName, aliases, ele);
}
// 解析bean标签为GenericBeanDefinition,标为 ⑥
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(
ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
// 如果不存在beanName那么根据Spring中提供的命名规则为当前bean生成对应的beanName
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
} else {
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null && beanName.startsWith(beanClassName)
&& beanName.length() > beanClassName.length()
&& !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
} catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
// 将GenericBeanDefinition、beanName、别名列表 放入BeanDefinitionHolder返回
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
⑥ 方法分析如下:
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
// 解析class属性
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
// 解析parent属性
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
// 创建 GenericBeanDefinition 类型的 BeanDefinition,用new的方式创建的,代码就不贴了~
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
/*
* 以下逻辑解析了bean标签所有属性封装在 GenericBeanDefinition 中,解析的代码很简单,不贴上来了~~
*/
// 解析 singleton、scope、abstract、lazy-init、autowire、
// depends-on、autowire-candidate、primary、init-method、
// destroy-method、factory-method、factory-bean 属性存在 BeanDefinition 中
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
// 解析 description 属性
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
// 解析 meta 属性以及 key、value,封装成 BeanMetadataAttribute 存在 BeanDefinition 中
parseMetaElements(ele, bd);
// 解析 lookup-method 属性以及 name、bean,
// 封装成 LookupOverride 存在 BeanDefinition 的 MethodOverrides 中
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
// 解析 replaced-method 属性以及 name、replacer、arg-type、match,
// 封装成 ReplaceOverride 存在 BeanDefinition 的 MethodOverrides 中
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
// 解析 constructor-arg 属性
parseConstructorArgElements(ele, bd);
// 解析 property 属性
parsePropertyElements(ele, bd);
// 解析 qualifier 属性
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
} catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
} catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
} catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
} finally {
this.parseState.pop();
}
return null;
}
⑤ BeanDefinitionReaderUtils.registerBeanDefinition 分析:(超级恶心,也是spring核心)
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
// 用beanName注册BeanDefinition,registry实现类是DefaultListableBeanFactory
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
// 别名拿出来注册到SimpleAliasRegistry中,前文分析过
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
// DefaultListableBeanFactory.java 的 registerBeanDefinition方法
@Override
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) { // true
try {
// 校验beanDefinition中MethodOverrides对应的方法是否存在
((AbstractBeanDefinition) beanDefinition).validate();
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(
beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
// DefaultListableBeanFactory 类持有 ConcurrentHashMap 类型的 beanDefinitionMap
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
// 处理已经注册过的beanName
if (existingDefinition != null) {
// 读取 allowBeanDefinitionOverriding 参数,是否允许beanName重复注册,这个参数前文讲解过,
// 如果不允许则抛出异常
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionStoreException(
beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition
+ "] for bean '" + beanName + "': There is already ["
+ existingDefinition + "] bound.");
} else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION,
// now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isWarnEnabled()) {
logger.warn("Overriding user-defined bean definition for bean '"
+ beanName + "' with a framework-generated bean definition: replacing ["
+ existingDefinition + "] with [" + beanDefinition + "]");
}
} else if (!beanDefinition.equals(existingDefinition)) {
if (logger.isInfoEnabled()) {
logger.info("Overriding bean definition for bean '" + beanName
+ "' with a different definition: replacing [" + existingDefinition
+ "] with [" + beanDefinition + "]");
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
// 覆盖之前注册的bean
this.beanDefinitionMap.put(beanName, beanDefinition);
} else {
/*
* spring 在 doCreate 方法(后文讲)创建 bean 时,
* 每创建一个 bean 就会在 AbstractBeanFactory.java 的
* 成员变量 alreadyCreated(ConcurrentHashMap扩展成的Set类型)内 add 一个 beanName。
*
* 这里正是判断 alreadyCreated.isEmpty() 来判断bean创建过程是否开始的。
*
* spring在创建Bean过程开始后再更改 beanDefinitionNames(ArrayList类型)
* 或 manualSingletonNames(LinkedHashSet类型)
* 都会提前用 hasBeanCreationStarted() 方法判断一下,
* 之后再对 beanDefinitionMap 加 synchronized 保证操作有序,
* 避免了多线程操作非线程安全集合带来的问题。
* 这里用新集合覆盖原集合的方式更新,而不是在原来的集合上直接操作,
* 我想大概是因为避免集合的fail-fast异常抛出吧 ~
*/
if (hasBeanCreationStarted()) {
// bean 创建过程已经开始了
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
// 在beanDefinitionMap中注册beanName
this.beanDefinitionMap.put(beanName, beanDefinition);
// 记录beanName
List<String> updatedDefinitions = new ArrayList<>(
this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
// 删除手动注册Singleton记录的beanName
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(
this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
} else {
// Still in startup registration phase
// bean 创建过程尚未开始,仍在启动注册阶段
// 在beanDefinitionMap中注册beanName
this.beanDefinitionMap.put(beanName, beanDefinition);
// 记录beanName
this.beanDefinitionNames.add(beanName);
// 删除手动注册Singleton记录的beanName
this.manualSingletonNames.remove(beanName);
}
// 容器初始化成功后会缓存所有beanDefinition数据,
// 这个数组中的BeanDefinition数据是不会变的,这里清空了这个缓存的集合。
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
// 如果BeanDefinition已经注册过,或者已经生成好的Singleton缓存包含这个beanName做重置操作:
// 清除由GenericBeanDefinition转换成的RootBeanDefinition缓存;
// 销毁beanName的Singleton缓存;
// 重置beanName对应的BeanDefinition作为父级的所有BeanDefinition的以上两种缓存(递归)。
resetBeanDefinition(beanName);
}
}
至此,默认标签已经解析完毕。
自定义标签解析
回顾一下调用自定义标签解析的地方:
// DefaultBeanDefinitionDocumentReader.java:
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);
}
}
接下来分析 delegate.parseCustomElement(root);
// BeanDefinitionParserDelegate.java:
@Nullable
public BeanDefinition parseCustomElement(Element ele) {
return parseCustomElement(ele, null);
}
@Nullable
public BeanDefinition parseCustomElement(
Element ele, @Nullable BeanDefinition containingBd) {
// 取得命名空间uri
String namespaceUri = getNamespaceURI(ele);
if (namespaceUri == null) {
return null;
}
// 用 命名空间uri 和 DefaultNamespaceHandlerResolver 解析出 NamespaceHandler
// this.readerContext.getNamespaceHandlerResolver()取得的是
// 前文分析 spring.handlers 时创建的 DefaultNamespaceHandlerResolver
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver()
.resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace ["
+ namespaceUri + "]", ele);
return null;
}
// 调用自定义命名空间处理器解析出BeanDefinition返回
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
// DefaultNamespaceHandlerResolver.java 的 resolve 方法
@Override
@Nullable
public NamespaceHandler resolve(String namespaceUri) {
// spring.handlers文件配置的命名空间和NamespaceHandler的对应关系集合
Map<String, Object> handlerMappings = getHandlerMappings();
// 用命名空间取得NamespaceHandler实现类
Object handlerOrClassName = handlerMappings.get(namespaceUri);
if (handlerOrClassName == null) {
return null;
} else if (handlerOrClassName instanceof NamespaceHandler) {
return (NamespaceHandler) handlerOrClassName;
} else {
String className = (String) handlerOrClassName;
try {
Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
throw new FatalBeanException(
"Class [" + className + "] for namespace [" + namespaceUri
+ "] does not implement the ["
+ NamespaceHandler.class.getName() + "] interface");
}
// 实例化
NamespaceHandler namespaceHandler =
(NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
namespaceHandler.init();
// 用实例化的namespaceHandler覆盖handlerMappings中String类型的class配置
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
} catch (ClassNotFoundException ex) {
throw new FatalBeanException(
"Could not find NamespaceHandler class [" + className
+"] for namespace [" + namespaceUri + "]", ex);
} catch (LinkageError err) {
throw new FatalBeanException(
"Unresolvable class definition for NamespaceHandler class ["
+ className + "] for namespace [" + namespaceUri + "]", err);
}
}
}
至此 解析及注册BeanDefinition 步骤已经全部完成 ~~,步骤2 取得了DefaultListableBeanFactory类型的ConfigurableListableBeanFactory,步骤2分析完毕。
步骤3:对BeanFactory进行各种功能填充
先贴上属性编辑器(PropertyEditor)的帖子:深入分析Spring属性编辑器(默认属性编辑器和自定义属性编辑器) 蟹蟹作者~~
// AbstractApplicationContext.java
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 设置beanFactory的ClassLoader为当前context的ClassLoader
beanFactory.setBeanClassLoader(getClassLoader());
// 设置beanFactory的表达式语言处理器,Spring3增加了表达式语言的支持,
// 默认可以使用#{bean.xxx}的形式来调用相关属性值。
beanFactory.setBeanExpressionResolver(
new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 为beanFactory增加了一个默认的propertyEditor,这个主要是对bean的属性等设置管理的一个工具
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
/*
* 添加BeanPostProcessor。
* ApplicationContextAwareProcessor的作用是
* 在bean实例化后,执行initMethod前(执行postProcessBeforeInitialization方法的时机)
* 如果bean实现了EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、
* ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware 中的一个或者多个接口,
* 按以上的罗列顺序调用各个接口的setxxxx方法,将ApplicationContext中相应属性设置到bean中。
* 参考文章:https://blog.csdn.net/andy_zhang2007/article/details/86287786
* 感谢作者!~
*/
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
/*
* 设置忽略自动装配的接口
* 当Spring将ApplicationContextAwareProcessor注册后,
* 那么在invokeAwareInterfaces方法中间接调用的Aware类已经不是普通的bean了,
* 如ResourceLoaderAware、ApplicationEventPublisherAware等,
* 那么当然需要在Spring做bean的依赖注入的时候忽略它们。而ignoreDependencyInterface的作用正是在此。
*/
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
/*
* 注册几个自动装配的特殊规则
* 当注册了依赖解析后,例如当注册了对BeanFactory.class的解析依赖后,当bean的属性注入的时候,
* 一旦检测到属性为BeanFactory类型便会将beanFactory的实例注入进去。
*/
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
/*
* 添加BeanPostProcessor。
* ApplicationListenerDetector直译是ApplicationListener探测器,
* 如果bean实现了ApplicationListener接口并且scope是单例,
* 在bean初始化后(执行BeanPostProcessor的postProcessAfterInitialization方法阶段)
* 它会被ApplicationListenerDetector捕捉到,
* 作为ApplicationListeners注册到容器的事件多播器(ApplicationEventMulticaster)中,
* 在bean销毁前(执行BeanPostProcessor的postProcessBeforeDestruction方法阶段)
* 把bean从应用上下文的事件多播器上移除。
* 参考文章:https://blog.csdn.net/andy_zhang2007/article/details/86374720
* 感谢作者!~
*/
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 增加对AspectJ的支持
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
// 添加默认的系统环境bean,将相关环境变量及属性注册以单例模式注册
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
步骤5:激活注册的BeanFactoryPostProcessor处理器
protected void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory) {
/*
* AbstractApplicationContext.java(当前类)持有beanFactoryPostProcessors集合
* 这个集合装着硬编码注册进来的BeanFactoryPostProcessor
* (因为addBeanFactoryPostProcessor方法没有人调用呀~~~)
* invokeBeanFactoryPostProcessors(下方法):
* 处理了硬编码和配置注册的所有BeanFactoryPostProcessor
*/
PostProcessorRegistrationDelegate
.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
// 如果发现叫 loadTimeWeaver 的bean,则增加对AspectJ的支持
if (beanFactory.getTempClassLoader() == null
&& beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(
new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(
new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
// PostProcessorRegistrationDelegate.java:
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory,
List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 如果有 BeanDefinitionRegistryPostProcessors,先调用
Set<String> processedBeans = new HashSet<>();
// beanFactory = DefaultListableBeanFactory, 这里是 true
// ================ 以下处理 BeanDefinitionRegistryPostProcessor 的实现类 =============
// ====== BeanDefinitionRegistryPostProcessor 继承自 BeanFactoryPostProcessor =======
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 常规 PostProcessors 集合
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// registryProcessor 集合
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 传进来的 beanFactoryPostProcessors 装着硬编码注册的 BeanFactoryPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
/*
* 如果实现了 BeanDefinitionRegistryPostProcessor
* (BeanDefinitionRegistryPostProcessor 继承自 BeanFactoryPostProcessor)
* 要先调用接口方法 postProcessBeanDefinitionRegistry
* 再把它放进 registryProcessors 集合
*/
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 放入 registryProcessor 集合
registryProcessors.add(registryProcessor);
}
else {
/*
* 不然直接放进 常规 PostProcessors 集合
*/
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// 不要在这里初始化FactoryBeans:我们需要保留所有未初始化的常规bean,
// 以使bean工厂后处理器适用于它们!
// 在实现 PriorityOrdered,Ordered 和其余的 BeanDefinitionRegistryPostProcessors 之间分开。
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 首先,调用实现 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors。
String[] postProcessorNames =
beanFactory.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(
beanFactory.getBean(
ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 放入 registryProcessor 集合
registryProcessors.addAll(currentRegistryProcessors);
// 集中调用 BeanDefinitionRegistryPostProcessor 的
// postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 接下来,调用实现 Ordered 的 BeanDefinitionRegistryPostProcessors
postProcessorNames = beanFactory.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)
&& beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(
beanFactory.getBean(
ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 放入 registryProcessor 集合
registryProcessors.addAll(currentRegistryProcessors);
// 集中调用 BeanDefinitionRegistryPostProcessor 的
// postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 最后,调用所有其他 BeanDefinitionRegistryPostProcessors,
// 直到不再出现其他BeanDefinitionRegistryPostProcessors
// 这里在不停的在工厂中取得BeanDefinitionRegistryPostProcessor类型的实例,
// 我想应该是这里调用invokeBeanDefinitionRegistryPostProcessors时又触发新的
// BeanDefinitionRegistryPostProcessor实现类注册到容器中,
// 这里不停调用invokeBeanDefinitionRegistryPostProcessors方法直到没有更新的为止。
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(
BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(
beanFactory.getBean(
ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 放入 registryProcessor 集合
registryProcessors.addAll(currentRegistryProcessors);
// 集中调用 BeanDefinitionRegistryPostProcessor 的
// postProcessBeanDefinitionRegistry 方法
invokeBeanDefinitionRegistryPostProcessors(
currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 现在,调用到目前为止处理的所有处理器的 postProcessBeanFactory 回调
// 先调用 实现了 BeanDefinitionRegistryPostProcessor 接口的
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 再调用普通的
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
} else {
// Invoke factory processors registered with the context instance.
// 如果不是 BeanDefinitionRegistry 的实现者,直接调用在上下文实例中注册的工厂处理器
invokeBeanFactoryPostProcessors(
beanFactoryPostProcessors, beanFactory);
}
// ========= 以下处理 BeanFactoryPostProcessor 的直接实现类 ========
// ====== 和上边处理 BeanDefinitionRegistryPostProcessor 类似,其实逻辑一毛一样~~ =======
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(
BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 实现 PriorityOrdered,Ordered 和其余的 BeanFactoryPostProcessors 之间分开。
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
} else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 清除缓存的合并bean定义,因为后处理器可能已经修改了原始元数据,例如,替换值中的占位符...
beanFactory.clearMetadataCache();
}
处理顺序:
调用硬编码的 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry
调用实现 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors 的 postProcessBeanDefinitionRegistry
调用实现 Ordered 的 BeanDefinitionRegistryPostProcessors 的 postProcessBeanDefinitionRegistry
调用所有其他 BeanDefinitionRegistryPostProcessors 的 postProcessBeanDefinitionRegistry
按上述顺序调用实现了 BeanDefinitionRegistryPostProcessor 的 BeanFactoryPostProcessor 的 postProcessBeanFactory
调用硬编码普通 BeanFactoryPostProcessor 的 postProcessBeanFactory
调用实现 PriorityOrdered 的 BeanFactoryPostProcessor 的 postProcessBeanFactory
调用实现 Ordered 的 BeanFactoryPostProcessor 的 postProcessBeanFactory
调用所有其他 BeanFactoryPostProcessor 的 postProcessBeanFactory
看起来很繁琐,其实就是按顺序调用各种BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor而已。
总结:先BeanDefinitionRegistryPostProcessor,后BeanFactoryPostProcessor。先硬编码,后配置文件注册。
BeanFactoryPostProcessor 使用示例:
PropertyPlaceholderConfigurer读取属性文件使用详解
也可以自定义 BeanFactoryPostProcessor 来统一处理 BeanFactory 中的 BeanDefinition,比如统一修改某个属性值之类的。
步骤6:注册拦截bean创建的bean处理器
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory,
AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(
BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
/*
* BeanPostProcessorChecker是一个普通的信息打印,可能会有些情况,
* 当Spring的配置中的后处理器还没有被注册就已经开始了bean的初始化时
* 便会打印出BeanPostProcessorChecker中设定的信息
*/
int beanProcessorTargetCount =
beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(
new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 将实现了 PriorityOrdered、 Ordered 和 普通的 BeanPostProcessor 分堆,之后按照顺序注册
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
} else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 首先注册实现了 PriorityOrdered 的
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 其次注册实现了 Ordered 的
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
// 现在最后注册所有常规的
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// 最后,注册所有 MergedBeanDefinitionPostProcessor 类型的 BeanPostProcessor,
// 并非重复注册,在 beanFactory.addBeanPostProcessor 中会先移除已经存在的 BeanPostProcessor
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 重新注册ApplicationListenerDetector
/*
* 添加BeanPostProcessor。
* ApplicationListenerDetector直译是ApplicationListener探测器,
* 如果bean实现了ApplicationListener接口并且scope是单例,
* 在bean初始化后(执行BeanPostProcessor的postProcessAfterInitialization方法阶段)
* 它会被ApplicationListenerDetector捕捉到,
* 作为ApplicationListeners注册到容器的事件多播器(ApplicationEventMulticaster)中,
* 在bean销毁前(执行BeanPostProcessor的postProcessBeforeDestruction方法阶段)
* 把bean从应用上下文的事件多播器上移除。
*/
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
步骤7:为上下文初始化Message源,支持i18n国际化
如何使用:
<!--
MessageSource常见的实现类有
org.Springframework.context.support.ResourceBundleMessageSource
org.Springframework.context.support.ReloadableResourceBundleMessageSource
前者通过资源名加载国际化资源,后者支持定时刷新,可在不重启系统下更新国际化资源。
-->
<!-- bean id = messageSource 必须写死 -->
<bean id="messageSource"
class="org.Springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>test/messages</value>
</list>
</property>
</bean>
在test文件夹下定义一组资源文件,比如:messages.property、messages_zh_CN.property
注意资源文件内容需要转码。
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
Object[] params = {"Jack", new GregorianCalendar().getTime()};
System.out.println(
"中国:" + context.getMessage("messageKey", params, Locale.CHINA));
System.out.println(
"美国:" + context.getMessage("messageKey", params, Locale.US));
这样就根据传入的Locale拿到对应资源文件中messageKey对应的value,传入参数format进value中输出出来。
源码解析:
// AbstractApplicationContext.java
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// MESSAGE_SOURCE_BEAN_NAME = "messageSource" 定义死的,所以配置时需要写死。
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 如果Factory中有 messageSource,那么把它拿出来记录在容器中。
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
// 使父容器也使用同样的
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
// 如果尚未注册父MessageSource,则仅将父上下文设置为父MessageSource。
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Using MessageSource [" + this.messageSource + "]");
}
} else {
//如果用户并没有定义配置文件,那么使用临时的DelegatingMessageSource以便于作为调用getMessage方法的返回
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
"': using default [" + this.messageSource + "]");
}
}
}
// 容器实现了 MessageSource 接口,可以通过容器直接使用MessageSource
@Override
public String getMessage(String code, @Nullable Object[] args,
@Nullable String defaultMessage, Locale locale) {
// getMessageSource() 返回配置的 messageSource
return getMessageSource().getMessage(code, args, defaultMessage, locale);
}
步骤8:初始化应用消息广播器
ApplicationListener用法:理解 Spring ApplicationListener 感谢作者~~
那么这里初始化的就是传播事件的组件:事件多路广播器
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
// 注册自定名为 applicationEventMulticaster 的 ApplicationEventMulticaster
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
} else {
// 否则用默认的 SimpleApplicationEventMulticaster
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(
APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
引用的例子中调用了:
context.publishEvent(event);
publishEvent 方法取得注册的 applicationEventMulticaster,调用实现的 multicastEvent() 方法来进行多路广播,也就是循环调用注册在容器中的 ApplicationListener 实现类,把 ApplicationEvent 传递进去,实现事件监听。
步骤10:查找listener bean,注册到消息广播器中
protected void registerListeners() {
// Register statically specified listeners first.
// 首先注册静态指定的侦听器。也就是硬编码进来的。
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 不要在这初始化bean:我们需要保留所有未经初始化的常规bean,让后处理器应用于它们!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
// 现在我们终于有了一个多播器,发布早期的应用程序事件......
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
步骤11:实例化剩下的单实例(非惰性的)
步骤2读取了xml文件,生成了BeanDefinition,但是还没针对这堆BeanDefinition生成单例的实例,现在就来做这件事情。前文在Factory中取bean时候总是调用:
public String[] getBeanNamesForType(
@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
方法,取得bean的名字,而没有取得bean的实例,就是为了在这统一实例化bean,在实例化bean的过程中调用一些设置好的钩子函数,统一处理。
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 初始化上下文的转换服务。
// CONVERSION_SERVICE_BEAN_NAME = "conversionService"
// 详解参见:https://blog.csdn.net/zhuqiuhui/article/details/82316720 感谢作者~
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 尽早初始化LoadTimeWeaverAware beans 以允许尽早注册其变换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
// 停止使用临时ClassLoader进行类型匹配。
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 冻结所有的bean定义,说明注册的bean定义将不被修改或任何进一步的处理。
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有剩余单例(非延迟)。
beanFactory.preInstantiateSingletons();
}
// DefaultListableBeanFactory.java 的 preInstantiateSingletons 方法
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 触发所有非惰性单例bean的初始化
for (String beanName : beanNames) {
// 用之前解析好的GenericBeanDefinition合并成RootBeanDefinition
// (可能设置了parent属性,父子bean的情况,做merge操作,用子bean属性覆盖父bean属性)
// getMergedLocalBeanDefinition 方法标注为 ⑩,后文一同分析
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
// FactoryBean的情况
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
// 判断FactoryBean需不需要提前初始化
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
} else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
// getBean 执行bean实例化逻辑
getBean(beanName);
}
}
} else {
// getBean 执行bean实例化逻辑
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
// 触发所有适用bean的后初始化回调...
// 就是调用所有实现了 SmartInitializingSingleton 接口的bean的 afterSingletonsInstantiated 方法。
for (String beanName : beanNames) {
// getSingleton 标注为 ⑦ 后文分析
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
} else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
到这儿程序回到 DefaultListableBeanFactory,getBean 方法为 BeanFactory 核心。
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
BeanFactory 提供了几种getBean重载方法,都会调用 doGetBean 方法,doGetBean为核心。
这里需要了解 FactoryBean 是怎么用的,推荐文章: 一分钟了解spring之FactoryBean
也需要简单了解下java安全管理器SecurityManager 、Spring中depends-on的作用是什么?
感谢作者!~
// AbstractBeanFactory.java
protected <T> T doGetBean(
final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// transformedBeanName 做了两件事:
// 1、删除工厂方法的&前缀(如果有)
// 2、如果是 alias,则转换成真实的 beanName
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
// 积极地尝试从缓存中获取单例bean,可能拿不到bean
/*
* bean没在缓存中并且bean也不在创建中(需要从头执行创建流程),返回null
* 或 beanName对应的bean根本不存在,返回null
* 或 bean正在创建中,但spring还没构建好 ObjectFactory,返回null
* 后文还会调用此方法,getSingleton 标注为 ⑦
*/
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
// 取到了实例
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
// 打出bean还未完全初始化好的log,
// 因为有循环引用存在,Factory没处理完就先返回了bean实例
logger.debug("Returning eagerly cached instance of singleton bean '"
+ beanName
+ "' that is not fully initialized yet - a consequence of a circular reference");
} else {
// log:返回了缓存的实例
// 程序走到这里,bean应该是初始化完成了的,
// 只不过在getSingleton时拿到的是创建过程中缓存的bean,
// 通过 isSingletonCurrentlyInCreation 的判断,现在应该是处理完了。
logger.debug("Returning cached instance of singleton bean '"
+ beanName + "'");
}
}
// 获取给定bean实例的对象,bean实例本身或其创建的对象(如果是 FactoryBean)。
// getObjectForBeanInstance 标注为 ⑧
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
// 如果原型(prototype)bean在当前线程正在创建中,抛出异常。
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 检查此工厂中是否存在bean定义。
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 当前BeanFactory没有beanName的BeanDefinition,检查父BeanFactory
// Not found -> check parent.
// 确定原始bean名称,将本地定义的别名解析为规范名称。
// originalBeanName方法 比 transformedBeanName 多做了一件事:
// 如果name以"&"开头,将转化后的标准名称加上"&"前缀
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
// 在父工厂取得bean
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
} else if (args != null) {
// Delegation to parent with explicit args.
// 使用显式args委托父级。
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
// No args -> delegate to standard getBean method.
// 没有args -> 委托给标准的getBean方法。
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
// 删除名为 beanName 的 mergedBeanDefinition缓存
// 让bean定义重新合并,以防万一其中一些元数据在此期间发生变化。
// 添加 alreadyCreated 标记
// markBeanAsCreated 标注为 ⑨
markBeanAsCreated(beanName);
}
try {
// 重新合并BeanDefinition
// getMergedLocalBeanDefinition 标注为 ⑩
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 校验是否是抽象类,是的话抛出异常
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 保证当前bean依赖的bean的初始化。
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
// 循环依赖的情况报错
throw new BeanCreationException(mbd.getResourceDescription(),
beanName,
"Circular depends-on relationship between '"
+ beanName + "' and '" + dep + "'");
}
// 记录依赖关系
registerDependentBean(dep, beanName);
try {
// 先初始化依赖的bean,递归getBean
getBean(dep);
} catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(),
beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
// 创建bean实例
if (mbd.isSingleton()) {
// Singleton 的情况
// 创建一个 ObjectFactory 隐藏实际创建bean的细节
// getSingleton 标注为 ⑪
sharedInstance = getSingleton(beanName, () -> {
try {
// createBean 标注为 ⑫
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
// 从单例缓存中显式删除实例:它可能已经被创建过程急切地放在那里,以允许循环引用解析。
// 也删除任何接收到bean的临时引用的bean。
destroySingleton(beanName);
throw ex;
}
});
// 获取给定bean实例的对象,bean实例本身或其创建的对象(如果是 FactoryBean)。
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
// Prototype 的情况
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
// 记录当前线程正在创建的 beanName
beforePrototypeCreation(beanName);
// 同上 createBean 标注为 ⑫
prototypeInstance = createBean(beanName, mbd, args);
} finally {
// 移除当前线程正在创建的 beanName
afterPrototypeCreation(beanName);
}
// 获取给定bean实例的对象,bean实例本身或其创建的对象(如果是 FactoryBean)。
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
// 非单例非原型 的情况
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
// 没找到Scope报错
throw new IllegalStateException(
"No Scope registered for scope name '" + scopeName + "'");
}
try {
// 由注册进来的Scope来保证bean的范围
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
});
// 获取给定bean实例的对象,bean实例本身或其创建的对象(如果是 FactoryBean)。
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName
+ "' is not active for the current thread; consider "
+ "defining a scoped proxy for this bean if you intend to"
+ " refer to it from a singleton",
ex);
}
}
} catch (BeansException ex) {
// 清除 alreadyCreated 标记
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
// 检查所需类型是否与实际bean实例的类型匹配。
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
} catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
先分析 ⑨ markBeanAsCreated 方法:
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
// 现在我们实际创建bean了,让bean定义重新合并...... 以防万一其中一些元数据在此期间发生变化。
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
⑦ getSingleton(String beanName)方法:
getSingleton(String beanName) 提取试着提取单例实例,或者调用构建好的ObjectFactory获取实例
// DefaultSingletonBeanRegistry.java
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
// 如果没有拿到,并且这个bean还正在创建中...
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
// DefaultSingletonBeanRegistry类 singletonObjects 属性
// 持有所有已经实例化的singleton集合(ConcurrentHashMap)
synchronized (this.singletonObjects) {
/*
* 在创建bean过程中,有自动注入的情况:
* 比如 A->B->C->A...,
* A类包含一个B类的属性,可是容器中B类还没有被实例化,
* 实例化A后(通过构建好的 ObjectFactory),将A实例放入 earlySingletonObjects,
* 去实例化B,将B实例放入 earlySingletonObjects,再去实例化C,
* 实例化C后发现C类包含有A类属性,那就直接从 earlySingletonObjects取得A就好了,
* 这样拿到的A实例就能保证是同一个。
* 解决了循环依赖问题。
*
* ObjectFactory 隐藏了bean的创建细节,在工厂中可能存在对bean的增强(AOP),
* 如果需要AOP则返回AOP后的代理实例,如果无AOP直接返回bean本身实例
*/
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 创建实例时会把实际创建过程隐藏在 ObjectFactory 中(程序主线不关心具体bean创建过程)
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 创建实例
singletonObject = singletonFactory.getObject();
// 记录在缓存中,earlySingletonObjects 和 singletonFactories 互斥
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
⑧ getObjectForBeanInstance 方法:
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
/*
* 有以下几种情况:
* Ⅰ: beanName = "a" A instanceof FactoryBean = true return A FactoryBean创建的实例
* Ⅱ: beanName = "a" A instanceof FactoryBean = false return A的单例实例
* Ⅲ: beanName = "&a" A instanceof FactoryBean = true return A FactoryBean
* Ⅳ: beanName = "&a" A instanceof FactoryBean = false return 报错
*/
// Don't let calling code try to dereference the factory if the bean isn't a factory.
// 对 FactoryBean 进行特殊情况处理和校验
// isFactoryDereference 方法检查 name 是否以"&"开头
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
// 如果name带"&"说明是FactoryBean,但是刚拿到的beanInstance不是个工厂,抛出异常,情况Ⅳ
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
// 现在我们有了bean实例,它可能是 普通bean 或 FactoryBean。
// 如果它是FactoryBean,我们使用它来创建bean实例,除非调用者实际上想要引用工厂。
if (!(beanInstance instanceof FactoryBean)
|| BeanFactoryUtils.isFactoryDereference(name)) {
// 情况Ⅱ、情况Ⅲ
return beanInstance;
}
// 情况Ⅰ: 通过FactoryBean创建实例
Object object = null;
if (mbd == null) { // true
// 从 FactoryBeans创建的单例对象缓存 中取得Bean实例
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
// 从工厂返回bean实例
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
// 缓存从FactoryBean获取的对象(如果它是单例)。
if (mbd == null && containsBeanDefinition(beanName)) {
// 获取合并后的BeanDefinition
// getMergedLocalBeanDefinition 方法标注为 ⑩
mbd = getMergedLocalBeanDefinition(beanName);
}
// 判断是否是合并的BeanDefinition,比如父子bean的情况
boolean synthetic = (mbd != null && mbd.isSynthetic());
// 从 FactoryBean 获取实例,合并bean不执行PostProcess
// getObjectFromFactoryBean 方法标注为 ⑬
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
⑩ getMergedLocalBeanDefinition 方法:
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName)
throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
// 首先快速检查并发映射,锁定最小。
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null) {
return mbd;
}
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
} else {
mbd = new RootBeanDefinition(bd);
}
} else {
// 设置了parent属性具有父子bean的情况
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
// 转换bean名称,删除工厂前缀,并将别名解析为规范名称。
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName)) {
// 递归取得父类的MergedBeanDefinition
pbd = getMergedBeanDefinition(parentBeanName);
} else {
// beanName 和 父beanName 重名的情况,尝试在父工厂寻找父类的MergedBeanDefinition
BeanFactory parent = getParentBeanFactory();
if (parent instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
} else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
}
}
} catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
// 深度拷贝
mbd = new RootBeanDefinition(pbd);
// 用子的属性覆盖父的属性
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
// 如果未配置scope属性,则设置默认单例。
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
// 包含在非单例bean中的bean本身不能是单例。
// 让我们在这里动态更正,因为这可能是外部bean的父子合并的结果,
// 在这种情况下,原始内部bean定义将不会继承合并的外部bean的单例状态。
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
// 暂时缓存合并的bean定义(稍后可能仍会重新合并以获取元数据更改)
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
return mbd;
}
}
⑬ getObjectFromFactoryBean 方法:
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
// 配置的FactoryBean是单例 并且 缓存已经存在beanName对应的单例
if (factory.isSingleton() && containsSingleton(beanName)) {
// 锁定 singletonObjects
synchronized (getSingletonMutex()) {
// 从 FactoryBeans创建的单例对象的缓存 中尝试取得
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
// 从给定FactoryBean中获取对象,也就是FactoryBean.getObject()
// doGetObjectFromFactoryBean 标注为 ⑭
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
// 只有在上面的getObject()调用期间没有进行后处理和存储(例如,由于自定义getBean调用触发的循环引用处理)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
} else {
// 非合并bean需要执行 PostProcess
if (shouldPostProcess) {
/*
* 此处判断bean是否在创建中的逻辑应该是为了避免递归调用死循环的情况。
* 用 singletonObjects 加锁,当前线程可以重入!
* 防止 BeanPostProcessor 的 postProcessAfterInitialization() 方法
* 再次以 beanName 从工厂中获取bean,进而再次执行 postProcessAfterInitialization() 导致死循环。
* 重入后不再执行 postProcessAfterInitialization,直接返回 object。
*/
// 判断单例bean当前是否正在创建
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
// 暂时返回没调用后处理的对象,而不是存储它。
return object;
}
// 添加正在创建状态
beforeSingletonCreation(beanName);
try {
// 执行 BeanPostProcessor 的 postProcessAfterInitialization
object = postProcessObjectFromFactoryBean(object, beanName);
} catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
} finally {
// 解除正在创建状态
afterSingletonCreation(beanName);
}
}
// 如果容器缓存了单例,那么把创建的实例也放进 FactoryBeans创建的单例对象的缓存
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
} else {
// 从给定FactoryBean中获取对象,也就是FactoryBean.getObject()
// doGetObjectFromFactoryBean 标注为 ⑭
Object object = doGetObjectFromFactoryBean(factory, beanName);
// 非合并bean需要执行PostProcess
if (shouldPostProcess) {
try {
// 执行 BeanPostProcessor 的 postProcessAfterInitialization
object = postProcessObjectFromFactoryBean(object, beanName);
} catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
// AbstractAutowireCapableBeanFactory.java 的 postProcessObjectFromFactoryBean 方法
@Override
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
return applyBeanPostProcessorsAfterInitialization(object, beanName);
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
⑭ doGetObjectFromFactoryBean 方法,它主要功能就是执行factory.getBean(),调用工厂生成实例:
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
} else {
// FactoryBean.getObject() 返回实例
object = factory.getObject();
}
} catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
} catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
// 不接受尚未完全初始化的FactoryBean的空值:许多FactoryBeans只返回null。
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
object = new NullBean();
}
return object;
}
回过头分析 doGetBean 方法中 的:
⑪ getSingleton(String beanName, ObjectFactory<?> singletonFactory) 方法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 尝试在单例对象的缓存中获取
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// singletonsCurrentlyInDestruction = false; 优雅关闭Context删除缓存的单例时会修改为true
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 添加当前bean正在创建中状态
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 调用工厂,返回新实例
singletonObject = singletonFactory.getObject();
newSingleton = true;
} catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
} catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 删除正在创建状态
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 添加单例bean的缓存
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
this.singletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
⑫ createBean 方法
doGetBean 调用 ⑪ 时构建了一个 ObjectFactory,这个ObjectFactory很简单,单纯的调用⑫ createBean 方法
// AbstractAutowireCapableBeanFactory.java
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// 确保此时实际解析了bean的class,并且在动态解析的类的情况下克隆beanDefinition,
// 该克隆对象不能存储在共享的合并bean定义中。
// 锁定class,根据设置的class属性或者根据className来解析Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
// 准备方法覆盖, lookup-method 或 replace-method 的情况
try {
// 验证及准备覆盖的方法
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 给BeanPostProcessors一个机会来返回代理来替代真正的实例
// resolveBeforeInstantiation 标注为 ⑮
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 当经过前置处理后返回的结果如果不为空,那么会直接略过后续的bean的创建而直接返回结果。
// AOP功能就是基于这里判断的。
if (bean != null) {
return bean;
}
} catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 创建指定的bean
// doCreateBean 标注为 ⑯
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
} catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
} catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
⑮ resolveBeforeInstantiation 方法:
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
// 确保此时实际解析了bean class。
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 确定给定bean定义的目标类型。
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
/*
* 执行所有 InstantiationAwareBeanPostProcessor 类型的
* BeanPostProcessor 的 postProcessBeforeInstantiation() 方法
*
* 执行这个方法后,bean或许成为了一个经过处理的代理bean,
* 可能是通过cglib生成的,也可能是通过其他技术生成的。
*/
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
/*
* 如果postProcessBeforeInstantiation返回的结果不是null!!!!
* 说明 InstantiationAwareBeanPostProcessor 可能对bean做了实例化处理
* 而不再doCreatBean生成实例,直接返回bean。
* 在返回bean前,尽可能地保证注册的 BeanPostProcessor 的
* postProcessAfterInitialization() 方法可以执行。
*/
/*
* 执行所有 BeanPostProcessor 的 postProcessAfterInitialization() 方法
*/
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(
Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(
Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
⑯ doCreateBean 方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
// 实例化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 从 未完成的FactoryBean实例的缓存 取得instanceWrapper
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 使用适当的实例化策略为指定的bean创建新实例:factory方法、构造函数自动装配或简单实例化。
// createBeanInstance 标注为 ⑰
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// 允许后处理器修改合并的bean定义。
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 执行 MergedBeanDefinitionPostProcessor类型的 BeanPostProcessor 的 postProcessMergedBeanDefinition() 方法
// 主要是寻找几个注解,@PostConstruct, @Autowire, @Value, @Resource,@PreDestroy 等
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
} catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 提前缓存单例以便能够解析循环引用,甚至在由BeanFactoryAware等生命周期接口触发时也是如此。
/*
* 是否需要提早曝光:当前bean是单例 && 允许循环依赖 && 当前bean正在创建中,检测循环依赖
* allowCircularReferences 可以通过硬编码方式设置进去:
* classPathXmlApplicationContext.setAllowBeanDefinitionOverriding(false);
*/
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
// 提早缓存 bean:beanName 允许解决潜在的循环引用
}
// 为避免后期循环依赖,可以在bean初始化完成前将创建实例的 ObjectFactory 加入单例工厂集合
// 这样后期如果有其他bean依赖该bean,可以从singletonFactories获取到bean。
// getEarlyBeanReference() 调用 SmartInstantiationAwareBeanPostProcessor 的 getEarlyBeanReference()方法
// 其中我们熟知的AOP就是在这里将advice动态织入bean中,若没有则直接返回bean,不做任何处理
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
// 初始化bean实例。
Object exposedObject = bean;
try {
// 对bean进行填充,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始依赖bean
// populateBean 标注为 ⑱
populateBean(beanName, mbd, instanceWrapper);
// 调用初始化方法,比如init-method
// initializeBean 标注为 ⑲
exposedObject = initializeBean(beanName, exposedObject, mbd);
} catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
} else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
// 如果 earlySingletonExposure,尝试从缓存获取该bean
// (一般存放在 singletonFactories 对象通过调用 getObject 把对象存入 earlySingletonObjects),
// 分别从 singletonObjects 和 earlySingletonObjects 获取对象
if (earlySingletonExposure) {
// ⑦ 的 getSingleton
Object earlySingletonReference = getSingleton(beanName, false);
// earlySingletonReference 只有在检测到有循环依赖的情况下才会不为空
if (earlySingletonReference != null) {
// 如果 exposedObject 没有在初始化方法中被改变,也就是没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 检测依赖
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
/*
* 因为bean创建后其所依赖的bean一定是已经创建的,
* actualDependentBeans 不为空 则表示当前bean创建后其依赖的bean却没有全部创建完,
* 也就是说存在循环依赖.
*/
if (!actualDependentBeans.isEmpty()) {
// 抛出Bean目前正在创建中异常
// 名为 beanName 的Bean已经作为循环引用的一部分注入其原始版本的其他bean [...],但最终被包装。
// 这意味着所述其他bean不使用bean的最终版本。
// 这通常是过于急切类型匹配的结果 - 例如,考虑使用'getBeanNamesOfType'并关闭'allowEagerInit'标志。
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
// 将bean注册为一次性。
try {
// 注册DisposableBean接口,在工厂关闭时调用的给定destroy方法。
// registerDisposableBeanIfNecessary 标注为 ⑳
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
protected void applyMergedBeanDefinitionPostProcessors(
RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
protected void addSingletonFactory(
String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
protected Object getEarlyBeanReference(
String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
doCreateBean 调用的 ⑰ createBeanInstance:
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 确保此时实际解析了bean class。
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 非public类且无public的构造方法标识类不允许被访问,抛出异常
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
// Support for functional instance supplier callback at BeanDefinition level
// 用supplier方式生成实例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 如果工厂方法不为空则使用工厂方法初始化策略
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 一个类有多个构造函数,每个构造函数都有不同的参数,
// 所以调用前需要先根据参数锁定构造函数或对应的工厂方法
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 如果已经解析过则使用解析好的构造函数方法不需要再次锁定
if (resolved) {
if (autowireNecessary) {
// 构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
} else {
// 使用默认构造函数构造
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// 需要根据参数解析构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 构造函数自动注入
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
// 没有特殊处理:只需使用no-arg构造函数。
return instantiateBean(beanName, mbd);
}
doCreateBean 调用的 ⑱ populateBean:
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
// 如果实例为null,但还有属性,抛出异常
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
} else {
// Skip property population phase for null instance.
// 跳过null实例的属性填充阶段。
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// 给InstantiationAwareBeanPostProcessors最后一次机会在属性设置前来改变bean
// 如:可以用来支持属性注入的类型
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 返回值为是否继续填充bean
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
// 如果后处理器发出停止填充命令则终止后续的执行
if (!continueWithPropertyPopulation) {
return;
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 如果该bean是支持按照名字或者类型自动注入的,
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
// 深度拷贝PropertyValues,当然对于对象来说只能公用一个
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
// 根据名称自动注入(byName),统一存入PropertyValues中
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
// 根据类型自动注入(byType),统一存入PropertyValues中
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 后处理器已经初始化
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 对所有需要依赖检查的属性进行后处理
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
// 依赖检查,对应depends-on属性,3.0已经弃用此属性
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
if (pvs != null) {
// 将属性应用到bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 寻找bw中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
// 递归初始化相关bean
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
// 注册依赖
registerDependentBean(propertyName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
} else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
//寻找bw中需要依赖注入的属性
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
if (Object.class != pd.getPropertyType()) {
// 探测指定属性的set方法
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在
// autowiredBeanNames中,当属性存在多个封装bean时如:
// @Autowired private List<A> aList;将会找到所有匹配A类型的bean并将其注入
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
// 注册依赖
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
} catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
doCreateBean 调用的 ⑲ initializeBean:
方法中4个步骤极为重要:
- 对特殊的bean处理:Aware、BeanClassLoaderAware、BeanFactoryAware
- 调用 BeanPostProcessor 的 postProcessBeforeInitialization() 方法
- 激活用户自定义的init方法:
1> 如果实现了 InitializingBean 接口则调用 afterPropertiesSet() 方法
2> 如果配置了自定义的 init-method 方法则调用这个方法 - 调用 BeanPostProcessor 的 postProcessAfterInitialization() 方法
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
} else {
// 对特殊的bean处理:Aware、BeanClassLoaderAware、BeanFactoryAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 应用后处理器,调用 BeanPostProcessor 的 postProcessBeforeInitialization() 方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 激活用户自定义的init方法
invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 后处理器应用,调用 BeanPostProcessor 的 postProcessAfterInitialization() 方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 首先会检查是否是InitializingBean,如果是的话需要调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
} else {
// 属性初始化后的处理
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 调用自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
doCreateBean 调用的 ⑳ registerDisposableBeanIfNecessary:
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
// 注册一个执行所有销毁的DisposableBean实现为给定的bean工作:DestructionAwareBeanPostProcessors,
// DisposableBean接口,自定义销毁方法。
/*
* 单例模式下注册需要销毁的bean,此方法中会处理实现DisposableBean的bean,
* 并且对所有的bean使用DestructionAwareBeanPostProcessors处理
* DisposableBeanDestructionAwareBeanPostProcessors
*/
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
} else {
// A bean with a custom scope...
// 具有自定义范围的bean ...
// 自定义scope的处理
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
步骤12:完成刷新过程
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清除上下文级资源缓存(例如来自扫描的ASM元数据)。
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 为此上下文初始化生命周期处理器。
// 当ApplicationContext启动或停止时,它会通过LifecycleProcessor来与所有声明的bean的周期做状态更新,
// 而在LifecycleProcessor的使用前首先需要初始化。
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 首先将刷新传播到生命周期处理器。
// 启动所有实现了Lifecycle接口的bean。
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 当完成ApplicationContext初始化的时候,要通过Spring中的事件发布机制来发出ContextRefreshedEvent事件,
// 以保证对应的监听器可以做进一步的逻辑处理。
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
// 向MBeanServer注册LiveBeansView,可以通过JMX来监控此ApplicationContext。
LiveBeansView.registerApplicationContext(this);
}
终于写完了…