SF如何使用BeanDefinition达成其目标IoC,我们通过跟踪BeanDefinition使用来了解。
使用起点
跟踪SF初始化过程,第一个点在:DefaultListableBeanFactory.preInstantiateSingletons。如下图:
RootBeanDefinition是运行时Spring BeanFactory使用的bean定义,可能是由多个相互继承的原始BeanDefinition(从配置元数据中解析生成的)合并创建而来。本质上可RootBeanDefinition当做运行时的“统一”bean定义视图。
注:此处生成bd(RootBeanDefinition)并没有传入到方法getBean(beanName),是因为第一次生成后就缓存在beanFactory,下次直接从缓存获得即可。
类-RootBeanDefinition
RootBeanDefinition继承于AbstractBeanDefinition,主要增强或限制:
1、不能有继承(都被合并):setParentName总是null;
2、确定bean解析器,包括注解、反射类型、class、工厂方法和supplier;
3、管理外部管理器:Member、初始化方法和销毁方法等;
@SuppressWarnings("serial")
public class RootBeanDefinition extends AbstractBeanDefinition {
//省略属性及11种构建函数
/* ParentName操作:ParentName必须为空(所有的继承类都合并成一个bean,这是RootBeanDefinition 的本质) */
@Override
public String getParentName() {
return null;
}
@Override
public void setParentName(@Nullable String parentName) {
if (parentName != null) {
throw new IllegalArgumentException("Root bean cannot be changed into a child bean with parent reference");
}
}
/* BeanDefinitionHolder(bean id、alias与BeanDefinition对应关系)操作*/
public void setDecoratedDefinition(@Nullable BeanDefinitionHolder decoratedDefinition) {
this.decoratedDefinition = decoratedDefinition;
}
@Nullable
public BeanDefinitionHolder getDecoratedDefinition() {
return this.decoratedDefinition;
}
/* bean的注解元素(含bean的所有注解)操作 */
public void setQualifiedElement(@Nullable AnnotatedElement qualifiedElement) {
this.qualifiedElement = qualifiedElement;
}
@Nullable
public AnnotatedElement getQualifiedElement() {
return this.qualifiedElement;
}
/** bean对应的解析类操作
解析类可以是ResolvableType 或者Class
ResolvableType:是Java.lang.reflect.Type的封装,最终将beanDefinition解析到对应Class的能力
Class:bean直接对应的Class
*/
public void setTargetType(@Nullable ResolvableType targetType) {
this.targetType = targetType;
}
public void setTargetType(@Nullable Class<?> targetType) {
this.targetType = (targetType != null ? ResolvableType.forClass(targetType) : null);
}
@Nullable
public Class<?> getTargetType() {
if (this.resolvedTargetType != null) {
return this.resolvedTargetType;
}
ResolvableType targetType = this.targetType;
return (targetType != null ? targetType.resolve() : null);
}
@Override
public ResolvableType getResolvableType() {
ResolvableType targetType = this.targetType;
if (targetType != null) {
return targetType;
}
ResolvableType returnType = this.factoryMethodReturnType;
if (returnType != null) {
return returnType;
}
Method factoryMethod = this.factoryMethodToIntrospect;
if (factoryMethod != null) {
return ResolvableType.forMethodReturnType(factoryMethod);
}
return super.getResolvableType();
}
/* 获得用于默认构造的首选构造函数(可以是多个)。如有必要,构造函数参数可以自动注入 */
@Nullable
public Constructor<?>[] getPreferredConstructors() {
return null;
}
/* 设置非重载方法工厂方法名称*/
public void setUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
this.isFactoryMethodUnique = true;
}
/* 设置重载方法工厂方法名称 */
public void setNonUniqueFactoryMethodName(String name) {
Assert.hasText(name, "Factory method name must not be empty");
setFactoryMethodName(name);
this.isFactoryMethodUnique = false;
}
/* 判定是否是工厂方法 */
public boolean isFactoryMethod(Method candidate) {
return candidate.getName().equals(getFactoryMethodName());
}
/* 设置工厂方法的解析方法器(Java Method) */
public void setResolvedFactoryMethod(@Nullable Method method) {
this.factoryMethodToIntrospect = method;
if (method != null) {
setUniqueFactoryMethodName(method.getName());
}
}
/* 获取工厂方法的解析方法器(Java Method) */
@Nullable
public Method getResolvedFactoryMethod() {
return this.factoryMethodToIntrospect;
}
/* 设置bean的实例生产者 */
@Override
public void setInstanceSupplier(@Nullable Supplier<?> supplier) {
super.setInstanceSupplier(supplier);
Method factoryMethod = (supplier instanceof InstanceSupplier<?> instanceSupplier ?
instanceSupplier.getFactoryMethod() : null);
if (factoryMethod != null) {
setResolvedFactoryMethod(factoryMethod);
}
}
// 标识BeanDefinition是否已被MergedBeanDefinitionPostProcessor处理过
public void markAsPostProcessed() {
synchronized (this.postProcessingLock) {
this.postProcessed = true;
}
}
// 注册外部管理的Member(Member代表a field or a method or a constructor)
public void registerExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedConfigMembers == null) {
this.externallyManagedConfigMembers = new LinkedHashSet<>(1);
}
this.externallyManagedConfigMembers.add(configMember);
}
}
// 判断是否外部管理Member
public boolean isExternallyManagedConfigMember(Member configMember) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedConfigMembers != null &&
this.externallyManagedConfigMembers.contains(configMember));
}
}
// 获得外部管理Set<Member>
public Set<Member> getExternallyManagedConfigMembers() {
synchronized (this.postProcessingLock) {
return (this.externallyManagedConfigMembers != null ?
Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedConfigMembers)) :
Collections.emptySet());
}
}
// 注册外部管理的初始化方法(例如,用JSR-250的注解是用jakarta.annotation.PostConstruct初始化)
public void registerExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedInitMethods == null) {
this.externallyManagedInitMethods = new LinkedHashSet<>(1);
}
this.externallyManagedInitMethods.add(initMethod);
}
}
// 判断是否是外部管理的初始化方法
public boolean isExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedInitMethods != null &&
this.externallyManagedInitMethods.contains(initMethod));
}
}
// 判断是否是外部管理的初始化方法(忽略方法的可见性)
boolean hasAnyExternallyManagedInitMethod(String initMethod) {
synchronized (this.postProcessingLock) {
if (isExternallyManagedInitMethod(initMethod)) {
return true;
}
if (this.externallyManagedInitMethods != null) {
for (String candidate : this.externallyManagedInitMethods) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot >= 0) {
String methodName = candidate.substring(indexOfDot + 1);
if (methodName.equals(initMethod)) {
return true;
}
}
}
}
return false;
}
}
// 获得外部管理的初始化方法
public Set<String> getExternallyManagedInitMethods() {
synchronized (this.postProcessingLock) {
return (this.externallyManagedInitMethods != null ?
Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedInitMethods)) :
Collections.emptySet());
}
}
// 解析可推测的bean销毁方法
public void resolveDestroyMethodIfNecessary() {
setDestroyMethodNames(DisposableBeanAdapter
.inferDestroyMethodsIfNecessary(getResolvableType().toClass(), this));
}
// 注册外部管理的销毁方法
public void registerExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
if (this.externallyManagedDestroyMethods == null) {
this.externallyManagedDestroyMethods = new LinkedHashSet<>(1);
}
this.externallyManagedDestroyMethods.add(destroyMethod);
}
}
// 判断是否是外部管理的销毁方法
public boolean isExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
return (this.externallyManagedDestroyMethods != null &&
this.externallyManagedDestroyMethods.contains(destroyMethod));
}
}
// 判断是否是外部管理的销毁方法(忽略方法的可见性)
boolean hasAnyExternallyManagedDestroyMethod(String destroyMethod) {
synchronized (this.postProcessingLock) {
if (isExternallyManagedDestroyMethod(destroyMethod)) {
return true;
}
if (this.externallyManagedDestroyMethods != null) {
for (String candidate : this.externallyManagedDestroyMethods) {
int indexOfDot = candidate.lastIndexOf('.');
if (indexOfDot >= 0) {
String methodName = candidate.substring(indexOfDot + 1);
if (methodName.equals(destroyMethod)) {
return true;
}
}
}
}
return false;
}
}
// 获得外部管理的销毁方法
public Set<String> getExternallyManagedDestroyMethods() {
synchronized (this.postProcessingLock) {
return (this.externallyManagedDestroyMethods != null ?
Collections.unmodifiableSet(new LinkedHashSet<>(this.externallyManagedDestroyMethods)) :
Collections.emptySet());
}
}
//克隆一个新的RootBeanDefinition
@Override
public RootBeanDefinition cloneBeanDefinition() {
return new RootBeanDefinition(this);
}
//类相等判断
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof RootBeanDefinition && super.equals(other)));
}
//类串化判断
@Override
public String toString() {
return "Root bean: " + super.toString();
}
}
方法-getMergedLocalBeanDefinition(String beanName)
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// 从缓存获取
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null && !mbd.stale) {
return mbd;
}
// 新建RootBeanDefinition
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
/* 过渡类 */
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
/** 真正实现合并BeanDefinition(主要合并继承关系)
* @param beanName:要合并的beanName
* @param bd:bean定义解析生成的BeanDefinition
* @param containingBd:对于内部类情况,包容该bean的BeanDefinition
*/
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
//同步执行
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;
// 不是内部类bean,从缓存获取一次(两次检测)
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
/* 合并处理 mbd.stale-需要合并标志 */
if (mbd == null || mbd.stale) {
// 处理前的mbd
previous = mbd;
if (bd.getParentName() == null) {
// bd没有父级
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition rootBeanDef) {
// 如果bd已经是RootBeanDefinition,直接克隆一份
mbd = rootBeanDef.cloneBeanDefinition();
}
else {
// 用bd生成RootBeanDefinition
mbd = new RootBeanDefinition(bd);
}
}
else {
// bd还有父级
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName)) {
// 有真正的父级bean,合并方式生成父级BeanDefinition (此处是递归调用,因此可以合并所有继承关系)
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
// 父级beanName同本身beanName相同,可能来自父级BeanFactory,从父级BeanFactory合并方式生成BeanDefinition
if (getParentBeanFactory() instanceof ConfigurableBeanFactory parent) {
pbd = parent.getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// 以父级bean生成新RootBeanDefinition,然后用孩子bd的重写(子类有的就覆盖父类),这样就把父子合并了(因为是递归调用,因此可以合并所有继承关系)
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(SCOPE_SINGLETON);
}
// 如果是内部类,scope同包容bean的scope
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// 非内部类进行缓存 (isCacheBeanMetadata()代表来自缓存的元数据)
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
if (previous != null) {
//处理前的mbd进行相关性处理(主要同bean解析器和工厂方法相关)
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
}
return mbd;
}
}
private void copyRelevantMergedBeanDefinitionCaches(RootBeanDefinition previous, RootBeanDefinition mbd) {
if (ObjectUtils.nullSafeEquals(mbd.getBeanClassName(), previous.getBeanClassName()) &&
ObjectUtils.nullSafeEquals(mbd.getFactoryBeanName(), previous.getFactoryBeanName()) &&
ObjectUtils.nullSafeEquals(mbd.getFactoryMethodName(), previous.getFactoryMethodName())) {
ResolvableType targetType = mbd.targetType;
ResolvableType previousTargetType = previous.targetType;
if (targetType == null || targetType.equals(previousTargetType)) {
mbd.targetType = previousTargetType;
mbd.isFactoryBean = previous.isFactoryBean;
mbd.resolvedTargetType = previous.resolvedTargetType;
mbd.factoryMethodReturnType = previous.factoryMethodReturnType;
mbd.factoryMethodToIntrospect = previous.factoryMethodToIntrospect;
}
}
}
创建bean实例使用
这是BeanDefinition真正作用的地方,入口在AbstractAutowireCapableBeanFactory.createBean。
创建入口
/* 创建bean实例 */
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
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
//如果mbd还没有解析Class,写回
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
// 对override方法做覆盖处理
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 实例化前处理
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 {
// 创建实例 注1
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("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);
}
}
注1:doCreateBean创建实例方法路径:doCreateBean->createBeanInstance->instantiateBean。中间方法是针对各种情况处理,最终实际在instantiateBean中生成bean实例
AbstractAutowireCapableBeanFactory.resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>… typesToMatch)
解析RootBeanDefinition对应的Class
// 过渡类
@Nullable
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
return doResolveBeanClass(mbd, typesToMatch);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}
// 解析bean的Class
@Nullable
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
throws ClassNotFoundException {
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;
boolean freshResolve = false;
if (!ObjectUtils.isEmpty(typesToMatch)) {
// 如果仅做类型检查(不生成bean实例),用临时ClassLoader检查处理。
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
dynamicLoader = tempClassLoader;
// freshResolve 为true,后续会进行Class解析
freshResolve = true;
if (tempClassLoader instanceof DecoratingClassLoader dcl) {
for (Class<?> typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
}
}
String className = mbd.getBeanClassName();
if (className != null) {
//className用表达式方式进行解析,解析出同mbd相关的class
Object evaluated = evaluateBeanDefinitionString(className, mbd);
if (!className.equals(evaluated)) {
/* 解析结果同className不一样 */
if (evaluated instanceof Class<?> clazz) {
// 解析出的是Class
return clazz;
}
else if (evaluated instanceof String name) {
// 解析出的是String
className = name;
freshResolve = true;
}
else {
throw new IllegalStateException("Invalid class name expression result: " + evaluated);
}
}
if (freshResolve) {
if (dynamicLoader != null) {
try {
//用动态加载器加载className对应的Class
return dynamicLoader.loadClass(className);
}
catch (ClassNotFoundException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
}
}
}
//用spring的ClassUtils加载className对应的Class
return ClassUtils.forName(className, dynamicLoader);
}
}
// 返回null (className不为空,前面处理了;为空,该方法实际也返回null
return mbd.resolveBeanClass(beanClassLoader);
}
真正创建
doCreateBean创建实例方法路径:doCreateBean->createBeanInstance->instantiateBean。中间方法是针对各种情况处理,最终在instantiateBean中生成bean实例
/** SF中,BeanWrapper是JavaBean的封装器,可提供分析和操作标准JavaBeans的操作:
1、能够获取和设置属性值(单独或批量)
2、获取属性描述符以及查询属性的可读性/可写性
*/
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
// 初始化一个bean实例 注1
Object beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
// 封装bean实例
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
}
}
注1:SF的bean实例初始化器是CglibSubclassingInstantiationStrategy,具体如何初始化参见:一起学SF框架系列5.8-模块Beans-bean实例化跟踪