目录
1. 注册BeanDefinition
2. 预初始化单例Bean
2.1 AbstractBeanFactory获取或者创建Bean实例
2.2 AbstractAutowireCapableBeanFactory#createBean创建bean
3. SimpleInstantiationStrategy#instantiate 实例化策略
3.1 CglibSubclassingInstantiationStrategy cglib实例化策略
DefaultListableBeanFactory类继承关系
1. 注册BeanDefinition
首先验证BeanDefinition, 验证通过之后, 判断BeanDefinition是否已经存在
- 存在的话, 判断是否重写和优先级, 然后将BeanDefinition维护到beanDefinitionMap中
- 不存在的话, 直接维护到beanDefinitionNames中
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@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) {
try {
//验证beanDefinition
//方法重写和bean重名
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
//bean定义已经存在
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
//bean定义不允许重写,则抛出异常
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
//BeanDefinition的role
//ROLE_APPLICATION = 0, 整个application重要组成部分, 通常是用户自定义Bean的ROLE
//ROLE_SUPPORT = 1, 一个大的配置的支撑部分, springboot引入的外部BeanDefinition
//ROLE_INFRASTRUCTURE = 2, springboot底层的BeanDefinition
if (logger.isInfoEnabled()) {
logger.info("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.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
//将新的BeanDefinition放入到map中
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
//已经开始创建bean
if (hasBeanCreationStarted()) {
//保证beanDefinitionNames线程安全
synchronized (this.beanDefinitionMap) {
//重新赋值beanDefinitionNames
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
//beanName已经被手动维护了
if (this.manualSingletonNames.contains(beanName)) {
//则更新manualSingletonNames
//使用注册的BeanDefinition替换手动维护的beanDefinition
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
//bean还没有开始创建
//仍然处于BeanDefinition注册阶段
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
//如果beanDefinition已经存在
//递归重置BeanDefinition以及其父BeanDefinition
resetBeanDefinition(beanName);
}
}
}
2. 预初始化单例Bean
在refreshContext()刷新应用上下文 finishBeanFactoryInitialization方法中, 执行了beanFactory.preInstantiateSingletons方法, 预初始化了非延时加载bean
首先从beanDefinitionNames中获取BeanDefinition列表, 递归将parent和child BeanDefinition合并成一个RootBeanDefinition, 然后判断BeanDefinition是否为factoryBean
- 如果是factoryBean, 先判断是否立即加载, 然后通过getBean()方法获取或生成bean
- 如果不是factoryBean, 直接通过getBean()方法获取或生成bean
如果beanSmartInitializingSingleton的子类, 那么在初始化之后执行SmartInitializingSingleton#afterSingletonsInstantiated方法
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
//预初始化单例Bean
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
//开辟一个新的List, 存储this.beanDefinitionNames
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
//触发单例bean的实例化
for (String beanName : beanNames) {
//xml定义的bean中有parent属性,
//getMergedLocalBeanDefinition会递归将parent和child BeanDefinition合并成一个RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象类, 单例的, 非延迟加载的才执行代码
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//FactoryBean工厂bean, 并不是直接返回一个Bean, 而是通过getObject()方法, 返回一个bean实例
if (isFactoryBean(beanName)) {
//获取factoryBean
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final 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方法
getBean(beanName);
}
}
}
else {
//不是工厂Bean
//立即调用getBean方法
getBean(beanName);
}
}
}
//触发SmartInitializingSingleton类型bean实例化之后的回调
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
//SmartInitializingSingleton的子类
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
//回调
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
//回调
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
}
2.1 AbstractBeanFactory获取或者创建Bean实例
先判断是否为factoryBean, 如果是的话, 那么会调用其getObject方法, 获取bean, 之后检查bean是否循环依赖, 如果当前beanFactory中获取不到bean, 会尝试递归从父factory中加载bean, 之后把bean标记为已创建, 然后先去实例化依赖的bean, 最后判断bean的scope并实例化bean
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
//获取Bean实例
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
//实际获取Bean实例的方法
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
//是否手工注册的单例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 + "'");
}
}
//如果是factoryBean的话, 那么会调用其getObject方法, 获取bean
//不是factoryBean的话, 直接返回当前bean
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
//检查是否循环依赖
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
//检查当前beanFactory中是否包含bean
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
//当前beanFactory中不包含bean
//递归从parent beanFactory中获取
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
//父beanFactory 获取bean
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// 父beanFactory 获取bean
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
//父beanFactory 获取bean
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
//标记bean已创建
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 先加载被依赖的bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
//...
}
registerDependentBean(dep, beanName);
try {
//递归实例化被依赖的bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
//...
}
}
}
// 创建bean实例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
//...
}
});
//如果是factoryBean, 那么通过其getObject()方法获取bean
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
//beanDefinition的scope设置为prototype
//每次都获取新的实例
Object prototypeInstance = null;
try {
//bean创建之前的回调
beforePrototypeCreation(beanName);
//创建bean
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
//bean创建之后的回调
afterPrototypeCreation(beanName);
}
//如果是factoryBean, 那么调用其getObject方法获取bean
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
//获取scope
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
//...
}
try {
Object scopedInstance = scope.get(beanName, () -> {
//bean创建之前的回调
beforePrototypeCreation(beanName);
try {
//创建bean
return createBean(beanName, mbd, args);
}
finally {
//bean创建之后的回调
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
//...
}
}
}
catch (BeansException ex) {
//创建出现异常, 清空缓存
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// requiredType和要创建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) {
//...
}
}
//返回bean
return (T) bean;
}
}
2.2 AbstractAutowireCapableBeanFactory#createBean
先解析beanClass, 尝试重写方法, 执行InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法, 可以使用代理生成新的bean
创建bean的过程中, 先执行MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition, 然后执行BeanPostProcessor#postProcessBeforeInitialization, 再判断要采取的实例化策略, 一种是反射, 另一种是cglib动态代理, 然后使用策略实例化bean, 再执行BeanPostProcessor#postProcessAfterInitialization, 对bean进行增强处理
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
//创建bean
@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;
// 解析BeanClass
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
//复制BeanDefinition
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
//方法重写
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
//...
}
try {
//执行InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation方法
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
//...
}
try {
//创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
//...
}
catch (Throwable ex) {
//...
}
}
//实际创建bean的方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// 初始化bean
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
//bean不是factoryBean
if (instanceWrapper == null) {
//创建bean实例
//使用对应的策略模式简单的创建新实例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//执行MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition方法
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
//...
}
mbd.postProcessed = true;
}
}
//循环依赖处理
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));
}
// 实例化bean
Object exposedObject = bean;
try {
//执行InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
//并处理autowireByName和autowireByType
//然后处理InstantiationAwareBeanPostProcessor#postProcessProperties
populateBean(beanName, mbd, instanceWrapper);
//实例化bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
//...
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
//依赖bean
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
//...
}
}
}
}
// 注册bean销毁方法
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
//...
}
return exposedObject;
}
//创建bean实例的方法
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 解析beanClass
Class<?> beanClass = resolveBeanClass(mbd, beanName);
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());
}
//使用Supplier#get()获取实例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//设置了factoryMethodName
//自定义factory生成bean实例
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
//简单实例化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) {
//构造函数解析
//调用ConstructorResolver#autowireConstructor
//先解析构造函数, 然后使用实例化策略实例化对象
return autowireConstructor(beanName, mbd, null, null);
}
else {
//简单实例化
//使用实例化策略实例化对象
return instantiateBean(beanName, mbd);
}
}
//判断是否通过构造函数实例化
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//构造函数实例化
//传入了参数
return autowireConstructor(beanName, mbd, ctors, args);
}
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
//无须特殊处理, 简单实例化bean
return instantiateBean(beanName, mbd);
}
//使用默认构造函数实例化bean
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
//获取bean初始化策略
//然后调用CglibSubclassingInstantiationStrategy#instantiate实例化bean
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
//继续初始化bean实例, 设置Aware对象, 设置init方法
//执行BeanPostProcessor#postProcessBeforeInitialization方法
//执行BeanPostProcessor#postProcessAfterInitialization方法
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
//如果是Aware类型的bean
//那么在bean中注入相应的对象
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//如果是InitializingBean类型的bean
//那么执行afterPropertiesSet方法
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;
}
}
3. SimpleInstantiationStrategy#instantiate
默认策略, 实例化对象, 如果有Override方法, 那么使用cglib实例化对象, 否则使用反射
public class SimpleInstantiationStrategy implements InstantiationStrategy {
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
//没有Override方法, 那么不使用cglib
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
//接口肯定有override方法
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 {
//有Override方法,那么使用cglib
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
}
3.1 CglibSubclassingInstantiationStrategy#instantiateWithMethodInjection
cglib实例化对象
//Cglib实例化策略
public class CglibSubclassingInstantiationStrategy extends SimpleInstantiationStrategy {
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Constructor<?> ctor, Object... args) {
//内部类CglibSubclassCreator实例化对象
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}
//静态内部类
private static class CglibSubclassCreator {
//实例化
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
Object instance;
if (ctor == null) {
//构造函数为空
//反射实例化
instance = BeanUtils.instantiateClass(subclass);
}
else {
try {
//通过构造函数实例化
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
instance = enhancedSubclassConstructor.newInstance(args);
}
catch (Exception ex) {
throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
}
}
Factory factory = (Factory) instance;
//设置回调
factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
return instance;
}
//cglib创建类
private Class<?> createEnhancedSubclass(RootBeanDefinition beanDefinition) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(beanDefinition.getBeanClass());
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
if (this.owner instanceof ConfigurableBeanFactory) {
ClassLoader cl = ((ConfigurableBeanFactory) this.owner).getBeanClassLoader();
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(cl));
}
enhancer.setCallbackFilter(new MethodOverrideCallbackFilter(beanDefinition));
enhancer.setCallbackTypes(CALLBACK_TYPES);
//创建类
return enhancer.createClass();
}
}
}