SmartInstantiationAwareBeanPostProcessor
接口继承自InstantiationAwareBeanPostProcessor
接口。
因此AbstractAutoProxyCreator
一般是通过InstantiationAwareBeanPostProcessor
接口的postProcessBeforeInstantiation
方法来给个机会返回代理对象,直接返回bean。否则待对象创建并初始化完成。再通过postProcessAfterInstantiation
方法使用动态代理根据实例对象创建增强的动态代理对象。
前置处理器一般返回null
,除非有TargetSource
,就是对象已经创建了,所以在第一次生成时应该把目光放在后置处理器上。
前置处理器 postProcessBeforeInstantiation
调用前置处理器
AbstractAutowireCapableBeanFactory#createBean
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
AbstractAutoProxyCreator#postProcessBeforeInstantiation
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
Object cacheKey = getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
// shouldSkip 调用 AspectJAwareAdvisorAutoProxyCreator 子类的 findCandidateAdvisors 寻找增强器。
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
// Create proxy here if we have a custom TargetSource.
// Suppresses unnecessary default instantiation of the target bean:
// The TargetSource will handle target instances in a custom fashion.
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
// 创建动态代理对象
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
return null;
}
}
后置处理器 postProcessAfterInstantiation
调用后置处理器
AbstractAutowireCapableBeanFactory#initializeBean
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
AbstractAutoProxyCreator#postProcessAfterInstantiation
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
wrapIfNecessary
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.