源码解析:Spring源码解析笔记启动过程(中)
Posted colodoo_纸伞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了源码解析:Spring源码解析笔记启动过程(中)相关的知识,希望对你有一定的参考价值。
本文由colodoo(纸伞)整理
QQ 425343603
Java学习交流群(717726984)
当前Spring源码版本是 5.2.10.RELEASE
承接上一篇文章源码解析:Spring源码解析笔记(二)启动过程(上)。
上一篇文章,我们把bean定义(beanDefinition)加载完毕了,下一步就是把我们加载的bean定实例化,我们跳过中间不必要的部分,直接到finishBeanFactoryInitialization这个方法。
如果想直接看核心部分是如何实现的,不想阅读前面的源码,可以反着看,从结论往前推。
完成 Bean 工厂初始化(finishBeanFactoryInitialization)
/**
* 完成此上下文的 bean 工厂的初始化,初始化所有剩余的单例 bean。
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 为此上下文初始化转换服务。
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));
}
// 如果没有 bean 后处理器,则注册一个默认的嵌入值解析器
// (例如 PropertyPlaceholderConfigurer bean)之前注册过任何:
// 在这一点上,主要用于注释属性值的解析。
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 尽早初始化 LoadTimeWeaverAware bean 以允许尽早注册它们的转换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止使用临时 ClassLoader 进行类型匹配。
beanFactory.setTempClassLoader(null);
// 允许缓存所有 bean 定义元数据,不需要进一步更改。
beanFactory.freezeConfiguration();
// 实例化所有剩余的(非延迟初始化)单例。(这里是实例化入口)
beanFactory.preInstantiateSingletons();
}
这部分前面都是准备工作我们简单翻译于一下,preInstantiateSingletons这个方法做了实例化操作,我们继续阅读preInstantiateSingletons。
预实例化单例(preInstantiateSingletons)
org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 触发所有非懒加载的单例bean的初始化...
for (String beanName : beanNames) {
// 获取bean定义
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 不是抽象类 并且 是单例 并且 不是延迟初始化
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 是工厂bean
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
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(beanName);
}
}
}
else {
// 一般的bean定义走这个入口
// (这里是实例化入口)
getBean(beanName);
}
}
}
这里主要是为了判断factoryBean以及相关的处理,我们一般的bean对象走最后的逻辑。进入到接下来的doGetBean具体的实现方法。
获得bean(doGetBean)
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
// 获得bean名称
String beanName = transformedBeanName(name);
Object bean;
// 急切地检查单例缓存是否有手动注册的单例.
// 从缓存中获取单例示例对象
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean \'" + beanName +
"\' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean \'" + beanName + "\'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 前面的逻辑在初始化过程中基本上不会走。
else {
// 判断是否目前正在创建的原型
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 检查父工厂
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 如果找不到,则找父类工厂
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
// 获取bean定义
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 检查合并 Bean 定义
checkMergedBeanDefinition(mbd, beanName, args);
// 保证当前 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 + "\'");
}
// 注册依赖项bean
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"\'" + beanName + "\' depends on missing bean \'" + dep + "\'", ex);
}
}
}
// 创建bean实例对象.
if (mbd.isSingleton()) {
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.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 省略
}
避免篇幅过长忽略了一部分注释,我们来梳理这部分的主要逻辑,这部分主要完成了下面几件事。
- 获取bean名称(beanName)
- 获取bean定义(beanDefinition)
- 传递用于创建对象的参数(args)
- 检查依赖项(depenOn)
- 首先实例化依赖项(getBean)
- 实例化依赖项(createBean)
- 实例化当前对象(createBean)
当我们阅读到createBean这个方法的时候就已经结束了,我们接下来继续详细阅读实例化bean的入口createBean。
创建 Bean(createBean)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean \'" + beanName + "\'");
}
RootBeanDefinition mbdToUse = mbd;
// 解析 Bean 类,获得真正的类
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 准备方法覆盖(不细究).
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 让 BeanPostProcessors 有机会返回一个代理而不是目标 bean 实例(不细究).
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 实例化bean入口(实例化入口)
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean \'" + beanName + "\'");
}
return beanInstance;
}
// 忽略...
}
这一部分就是要根据bean名称(beanName)、bean定义(beanDeifinition)找出真正可用的类。
接下来继续阅读doCreateBean,具体的创建bean实例的方法。
创建Bean(doCreateBean)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
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.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean \'" + beanName +
"\' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
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);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
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);
}
}
if (!actualDependentBeans.isEmpty()) {
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 " +
"\'getBeanNamesForType\' with the \'allowEagerInit\' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
后面省略了两个部分,具体的方法名称我列出来,基本都是创建bean前的预处理,不用细究。
创建 Bean 实例(createBeanInstance)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
实例化 Bean(instantiateBean)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean
真正实例化的工具方法如下两个方法,很直接的说就是利用反射知识,构造函数创建实例对象。
实例化(instantiate)
org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate(org.springframework.beans.factory.support.RootBeanDefinition, java.lang.String, org.springframework.beans.factory.BeanFactory)
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 如果没有覆盖,不要用 CGLIB 覆盖类。
if (!bd.hasMethodOverrides()) {
// 构造函数变量
Constructor<?> constructorToUse;
// 构造函数参数锁(上锁)
synchronized (bd.constructorArgumentLock) {
// 解析构造函数或工厂方法赋值给构造函数变量
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
// 如果为空
if (constructorToUse == null) {
// 获得bean定义的类
final Class<?> clazz = bd.getBeanClass();
// 如果类是个接口,抛出异常
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
// 如果系统安全管理存在,则提升权限获得构造方法
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
// 获得构造方法
constructorToUse = clazz.getDeclaredConstructor();
}
// 获得构造方法
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 根据构造函数实例化对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// 必须生成CGLIB 子类(跟aop有关)。s.=
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
这一部分是获取构造方法,下一部分通过构造方法实例化对象。
实例化类(instantiateClass)
org.springframework.beans.BeanUtils#instantiateClass(java.lang.reflect.Constructor<T>, java.lang.Object...)
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
// 判断是否为空
Assert.notNull(ctor, "Constructor must not be null");
try {
// 设置构造函数可访问
ReflectionUtils.makeAccessible(ctor);
// Kotlin方式处理(忽略)
if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
return KotlinDelegate.instantiateClass(ctor, args);
}
else {
// 获取参数类型数组
Class<?>[] parameterTypes = ctor.getParameterTypes();
// 获取的参数类型数组小于传递的参数对象数组,则抛错
Assert.isTrue(args.length <= parameterTypes.length, "Can\'t specify more arguments than constructor parameters");
// 初始化传递的参数
Object[] argsWithDefaultValues = new Object[args.length];
// 遍历参数
for (int i = 0 ; i < args.length; i++) {
if (args[i] == null) {
// 把对象赋值给
Class<?> parameterType = parameterTypes[i];
// 处理原始类型
// {Class@1933} "int" -> {Integer@1934} 0
// {Class@1935} "boolean" -> {Boolean@1894} false
// {Class@1936} "short" -> {Short@1937} 0
// {Class@1938} "byte" -> {Byte@1939} 0
// {Class@1940} "long" -> {Long@1941} 0
argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
}
else {
// 传递的参数对象赋值给获获取的参数类型中
argsWithDefaultValues[i] = args[i];
}
}
// 通过构造方法实例化对象
return ctor.newInstance(argsWithDefaultValues);
}
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
看到ctor.newInstance,就相当于我们做了new Object()这样的操作;至此,就完成了我们bean的实例化操作。
总结
最后说几个我们需要关注的几个方法,如果主要关注bean对象的实例化,可以在这个方法上加上断点。
org.springframework.beans.BeanUtils#instantiateClass(java.lang.reflect.Constructor<T>, java.lang.Object...)
以下是调用栈,可以根据这个相应的源码行数去阅读,从最后一行往前面阅读。
instantiate:87, SimpleInstantiationStrategy (org.springframework.beans.factory.support)
instantiateBean:1310, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBeanInstance:1213, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:556, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:516, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean$0:324, AbstractBeanFactory (org.springframework.beans.factory.support)
getObject:-1, 1010931249 (org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$10)
getSingleton:234, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:322, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:202, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:897, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:879, AbstractApplicationContext (org.springframework.context.support)
refresh:551, AbstractApplicationContext (org.springframework.context.support)
至此,所有的定义的bean对象都完成了实例化,但是还是不能直接被我们所使用,因为我们常常 用到的一些依赖属性值还未被注入。
下一章,我们来研究属性注入和初始化是怎么实现的。
以上是关于源码解析:Spring源码解析笔记启动过程(中)的主要内容,如果未能解决你的问题,请参考以下文章