Spring AOP基础组件 AbstractAutoProxyCreator
相关阅读
简介
使用AOP代理对象包装有资格的Bean的BeanPostProcessor
实现,再调用Bean之前会委派给特定的拦截器;
AbstractAutoProxyCreator
会区分两种拦截器:
- 通用拦截器,被所有它创建的代理所共享,通过
interceptorNames
属性配置,可以没有; - 特定拦截器,只应用于特定的Bean实例;
继承自ProxyProcessorSupport
,具有ProxyConfig
中动态代理相关的配置属性;
实现了SmartInstantiationAwareBeanPostProcessor
接口,实现了实例化前后置处理,属性的后置处理;
拦截器都是通过Bean name而不是Bean 引用进行配置,这方便正确地处理多例类型的Advisor
、Interceptor
;
子类可以重写判断Bean是否可以被代理的策略,比如:根据类型,根据Bean name,根据BeanDefinition
等;也可以添加额外的拦截器;
源码
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
// 表示不代理
@Nullable
protected static final Object[] DO_NOT_PROXY = null;
// 表示无特定拦截器
protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0];
// 默认是GlobalAdvisorAdapterRegistry
private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();
// 通用拦截器的Bean name,默认无通用拦截器
private String[] interceptorNames = new String[0];
// 通用拦截器是否在特定拦截器之前应用标识,默认为true
private boolean applyCommonInterceptorsFirst = true;
@Override
@Nullable
public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
if (this.proxyTypes.isEmpty()) {
// 当前缓存信息为空,则直接返回null
return null;
}
Object cacheKey = getCacheKey(beanClass, beanName);
// 尝试从缓存中获取
return this.proxyTypes.get(cacheKey);
}
// Bean实例化前处理
@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)) {
// 已经处理过,直接返回null
return null;
}
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
// 基础的类型或者不需要代理的类
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
// 如果存在targetSource,则需要创建代理
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
// 获取特定于该Bean的拦截器,没有则返回PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
// 创建代理
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
// 缓存代理的类型
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
return null;
}
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
// 如果Bean被代理过,则需要创建代理
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
// TargetSource无需包装
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
// 不需要代理无需包装
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
// 基础的类型或者不需要代理的类,无需包装
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// 获取特定于Bean的拦截器,如果为null则无需代理
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
// 存在特定拦截器(空数组也算存在),则需要创建代理
this.advisedBeans.put(cacheKey, Boolean.TRUE);
// 创建代理
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
// 缓存代理类型
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
// 不存在特定拦截器,无需包装
// 缓存不包装的类型
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
// 是否是不需要代理的基础类型
protected boolean isInfrastructureClass(Class<?> beanClass) {
// 默认Advice、Pointcut、Advisor、AopInfrastructureBeans无需代理
// 子类可重写该逻辑
boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
Pointcut.class.isAssignableFrom(beanClass) ||
Advisor.class.isAssignableFrom(beanClass) ||
AopInfrastructureBean.class.isAssignableFrom(beanClass);
if (retVal && logger.isTraceEnabled()) {
logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
}
return retVal;
}
// 自动代理是否需要跳过本类
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
}
// 获取定制的TargetSource
@Nullable
protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
if (this.customTargetSourceCreators != null &&
this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
// 存在定制的TargetSourceCreator,则尝试获取定制的TargetSource
for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
TargetSource ts = tsc.getTargetSource(beanClass, beanName);
if (ts != null) {
if (logger.isTraceEnabled()) {
logger.trace("TargetSourceCreator [" + tsc +
"] found custom TargetSource for bean with name '" + beanName + "'");
}
return ts;
}
}
}
// 没有发现定制的TargetSource
return null;
}
protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
@Nullable Object[] specificInterceptors, TargetSource targetSource) {
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
}
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (proxyFactory.isProxyTargetClass()) {
// 处理引介通知
if (Proxy.isProxyClass(beanClass)) {
for (Class<?> ifc : beanClass.getInterfaces()) {
proxyFactory.addInterface(ifc);
}
}
}
else {
// 未设置proxyTargetClass标识,则进行默认检查
if (shouldProxyTargetClass(beanClass, beanName)) {
// 设置proxyTargetClass标识
proxyFactory.setProxyTargetClass(true);
}
else {
// 评估是否有可用的代理接口
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
// 根据通用拦截器和特定拦截器创建Advisor
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors);
proxyFactory.setTargetSource(targetSource);
// 可由子类实现定制化处理
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
// 设置preFiltered标识,表示拦截器都有效
proxyFactory.setPreFiltered(true);
}
// Use original ClassLoader if bean class not locally loaded in overriding class loader
ClassLoader classLoader = getProxyClassLoader();
if (classLoader instanceof SmartClassLoader && classLoader != beanClass.getClassLoader()) {
classLoader = ((SmartClassLoader) classLoader).getOriginalClassLoader();
}
// 通过ProxyFactory创建代理
return proxyFactory.getProxy(classLoader);
}
protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
// 根据Bean name获取通用拦截器
Advisor[] commonInterceptors = resolveInterceptorNames();
List<Object> allInterceptors = new ArrayList<>();
if (specificInterceptors != null) {
// 特定拦截器存在(空数组认为也存在)时,才考虑添加拦截器
if (specificInterceptors.length > 0) {
// 添加特定拦截器
allInterceptors.addAll(Arrays.asList(specificInterceptors));
}
if (commonInterceptors.length > 0) {
// 添加通用拦截器到合适位置
if (this.applyCommonInterceptorsFirst) {
allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
}
else {
allInterceptors.addAll(Arrays.asList(commonInterceptors));
}
}
}
if (logger.isTraceEnabled()) {
int nrOfCommonInterceptors = commonInterceptors.length;
int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0);
logger.trace("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors +
" common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
}
Advisor[] advisors = new Advisor[allInterceptors.size()];
for (int i = 0; i < allInterceptors.size(); i++) {
// 适配拦截器为Advisor
advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
}
return advisors;
}
// 获取特定于Bean的拦截器
@Nullable
protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName,
@Nullable TargetSource customTargetSource) throws BeansException;
}
实现子类
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator
public class DefaultAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator implements BeanNameAware
public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator
BeanNameAutoProxyCreator
简介
基于Bean name来判断是否需要进行代理,支持通配符*
匹配;
当需要代理时,BeanNameAutoProxyCreator
就返回PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
,否则返回null
,仅使用通用拦截器,通过interceptorNames
属性设置;
核心代码
public class BeanNameAutoProxyCreator extends AbstractAutoProxyCreator {
private static final String[] NO_ALIASES = new String[0];
// 需要代理的Bean name,支持通配符*
@Nullable
private List<String> beanNames;
@Override
protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
// 需要匹配配置的名称
return (isSupportedBeanName(beanClass, beanName) ?
super.getCustomTargetSource(beanClass, beanName) : null);
}
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
// 匹配配置的名称则需要代理(空拦截器数组),否则不需要
return (isSupportedBeanName(beanClass, beanName) ?
PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS : DO_NOT_PROXY);
}
private boolean isSupportedBeanName(Class<?> beanClass, String beanName) {
if (this.beanNames != null) {
// 判断是否是FactoryBean类型
boolean isFactoryBean = FactoryBean.class.isAssignableFrom(beanClass);
// 遍历配置的Bean name
for (String mappedName : this.beanNames) {
if (isFactoryBean) {
// 如果是FactoryBean,则Bean name会有前缀&
if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
continue;
}
// 去掉前缀&,再进行后续匹配逻辑
mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
}
if (isMatch(beanName, mappedName)) {
// 匹配上,则表示支持该Bean name
return true;
}
}
BeanFactory beanFactory = getBeanFactory();
// 获取该Bean name的别名
String[] aliases = (beanFactory != null ? beanFactory.getAliases(beanName) : NO_ALIASES);
// 遍历别名,进行匹配
for (String alias : aliases) {
for (String mappedName : this.beanNames) {
if (isMatch(alias, mappedName)) {
// 别名匹配上,则表示支持该Bean name
return true;
}
}
}
}
return false;
}
protected boolean isMatch(String beanName, String mappedName) {
// 借助PatternMatchUtils实现通配符*匹配
return PatternMatchUtils.simpleMatch(mappedName, beanName);
}
}
AbstractAdvisorAutoProxyCreator
简介
借助AopUtils
查找可以应用于指定Bean的特定Advisor
,并支持子类添加额外的Advisor
;
返回的Advisor
数组是经过AnnotationAwareOrderComparator
排序的,如果匹配的Advisor
未标注@Order
注解或者未实现Ordered
接口,则会放在advisor chain的尾部,且无序;
核心代码
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
@Override
@Nullable
protected Object[] getAdvicesAndAdvisorsForBean(
Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
}
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
// 获取BeanFactory中所有的Advisor Bean
List<Advisor> candidateAdvisors = findCandidateAdvisors();
// 获取可以应用到指定Bean的Advisor Bean
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
// 扩展Advisor
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
// 排序
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
protected List<Advisor> findCandidateAdvisors() {
Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
// 借助BeanFactoryAdvisorRetrievalHelper实现获取BeanFactory中所有的Advisor Bean
return this.advisorRetrievalHelper.findAdvisorBeans();
}
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
// 借助AopUtils获取可以应用到指定Bean的Advisor Bean
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}
protected boolean isEligibleAdvisorBean(String beanName) {
// 指定的Advisor都有资格在首位进行代理
return true;
}
protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
// 默认使用AnnotationAwareOrderComparator进行排序,子类可重写排序逻辑
AnnotationAwareOrderComparator.sort(advisors);
return advisors;
}
// 扩展Advisor,子类可重写来添加额外的Advisor
protected void extendAdvisors(List<Advisor> candidateAdvisors) {
}
@Override
protected boolean advisorsPreFiltered() {
// 总是返回true
return true;
}
}
DefaultAdvisorAutoProxyCreator
简介
AbstractAdvisorAutoProxyCreator
的默认实现,重写了isEligibleAdvisorBean
方法,支持根据配置的Bean name前缀过滤Advisor
Bean;
核心代码
public class DefaultAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator implements BeanNameAware {
public static final String SEPARATOR = ".";
// 开启前缀匹配标识
private boolean usePrefix = false;
Advisor Bean name前缀
@Nullable
private String advisorBeanNamePrefix;
@Override
public void setBeanName(String name) {
// If no infrastructure bean name prefix has been set, override it.
if (this.advisorBeanNamePrefix == null) {
// 设置Advisor Bean name前缀
this.advisorBeanNamePrefix = name + SEPARATOR;
}
}
@Override
protected boolean isEligibleAdvisorBean(String beanName) {
if (!isUsePrefix()) {
// 未开启前缀匹配,则全满足
return true;
}
String prefix = getAdvisorBeanNamePrefix();
// 开启前缀匹配,则Advisor Bean name必须以配置的前缀为前缀才满足
return (prefix != null && beanName.startsWith(prefix));
}
}
InfrastructureAdvisorAutoProxyCreator
简介
InfrastructureAdvisorAutoProxyCreator
重写了isEligibleAdvisorBean
方法,仅允许ROLE_INFRASTRUCTURE
类型的Advisor
Bean;
核心代码
public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
@Override
protected boolean isEligibleAdvisorBean(String beanName) {
return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) &&
// 仅ROLE_INFRASTRUCTURE的Advisor Bean满足
this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
}
}
AspectJAwareAdvisorAutoProxyCreator
简介
暴露AspectJ调用上下文,且支持AspectJ的Advice
优先级规则;
解析aop 命名空间的配置信息时生成;
核心代码
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
private static final Comparator<Advisor> DEFAULT_PRECEDENCE_COMPARATOR = new AspectJPrecedenceComparator();
@Override
protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = new ArrayList<>(advisors.size());
for (Advisor advisor : advisors) {
partiallyComparableAdvisors.add(
// 使用PartiallyComparableAdvisorHolder包装Advisor,以便后续排序
new PartiallyComparableAdvisorHolder(advisor, DEFAULT_PRECEDENCE_COMPARATOR));
}
// 使用AspectJPrecedenceComparator排序
List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors);
if (sorted != null) {
// 存在排序结果
List<Advisor> result = new ArrayList<>(advisors.size());
// 提取排序后的Advisor链表
for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) {
result.add(pcAdvisor.getAdvisor());
}
return result;
}
else {
// 排序失败,则使用父类排序方法
return super.sortAdvisors(advisors);
}
}
@Override
protected void extendAdvisors(List<Advisor> candidateAdvisors) {
// 添加ExposeInvocationInterceptor如果需要的话,以便支持AspectJ切点表达式和AspectJ通知
AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
}
@Override
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
List<Advisor> candidateAdvisors = findCandidateAdvisors();
for (Advisor advisor : candidateAdvisors) {
// 如果是AspectJPointcutAdvisor Bean,则需要跳过
if (advisor instanceof AspectJPointcutAdvisor &&
((AspectJPointcutAdvisor) advisor).getAspectName().equals(beanName)) {
return true;
}
}
// 再调用父类方法进行判断
return super.shouldSkip(beanClass, beanName);
}
// 支持Advisor比较
private static class PartiallyComparableAdvisorHolder implements PartialComparable {
private final Advisor advisor;
private final Comparator<Advisor> comparator;
public PartiallyComparableAdvisorHolder(Advisor advisor, Comparator<Advisor> comparator) {
this.advisor = advisor;
this.comparator = comparator;
}
@Override
public int compareTo(Object obj) {
Advisor otherAdvisor = ((PartiallyComparableAdvisorHolder) obj).advisor;
return this.comparator.compare(this.advisor, otherAdvisor);
}
@Override
public int fallbackCompareTo(Object obj) {
return 0;
}
public Advisor getAdvisor() {
return this.advisor;
}
}
}
AnnotationAwareAspectJAutoProxyCreator
简介
处理AspectJ注解定义的切面以及Spring的Advisor
;
如果定义了<aop:include>
元素,则仅那些名称于包含模式匹配的@AspectJ Bean才会被当作定义用于Spring自动代理的切面;
核心代码
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {
// 配置的模式,正则形式
@Nullable
private List<Pattern> includePatterns;
// 设置模式
public void setIncludePatterns(List<String> patterns) {
this.includePatterns = new ArrayList<>(patterns.size());
for (String patternText : patterns) {
this.includePatterns.add(Pattern.compile(patternText));
}
}
@Override
protected List<Advisor> findCandidateAdvisors() {
// Add all the Spring advisors found according to superclass rules.
List<Advisor> advisors = super.findCandidateAdvisors();
// Build Advisors for all AspectJ aspects in the bean factory.
if (this.aspectJAdvisorsBuilder != null) {
// 为所有AspectJ切面构建Advisor
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
@Override
protected boolean isInfrastructureClass(Class<?> beanClass) {
return (super.isInfrastructureClass(beanClass) ||
// AspectJ切面类也认为是基础类型
(this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
}
protected boolean isEligibleAspectBean(String beanName) {
if (this.includePatterns == null) {
// 未配置匹配模式,则认为都满足
return true;
}
else {
// 配置了匹配模式,则必须匹配上配置的模式才认为满足
for (Pattern pattern : this.includePatterns) {
if (pattern.matcher(beanName).matches()) {
return true;
}
}
return false;
}
}
// 将AspectJ切面转换为Advisor的适配器
private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder {
public BeanFactoryAspectJAdvisorsBuilderAdapter(
ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {
super(beanFactory, advisorFactory);
}
@Override
protected boolean isEligibleBean(String beanName) {
return AnnotationAwareAspectJAutoProxyCreator.this.isEligibleAspectBean(beanName);
}
}
}