aopalliance
aopalliance对AOP做了最高层次的抽象,定义了两个重要概念:Advice跟Joinpoint
Advice:指的是要做何种操作,是顶级的通知接口,有个重要的子接口:MethodInterceptor
Joinpoint:把拦截器跟被拦截的方法编织到一起,proceed方法会执行所有拦截器逻辑跟被拦截方法的逻辑,有个重要的子接口:MethodInvocation
接口继承关系上,Interceptor继承Adivce接口,表示拦截器,MethodInterceptor跟ConstructorInterceptor继承Intercepter接口,分别表示拦截方法调用跟拦截构造器调用
MethodInterceptor只有一个invoke方法,invoke方法里可以调用MethodInvocation#proceed方法调用下一个拦截器或者直接调用被拦截的方法
@FunctionalInterface
public interface MethodInterceptor extends Interceptor {
/**
* Implement this method to perform extra treatments before and
* after the invocation. Polite implementations would certainly
* like to invoke {@link Joinpoint#proceed()}.
* @param invocation the method invocation joinpoint
* @return the result of the call to {@link Joinpoint#proceed()};
* might be intercepted by the interceptor
* @throws Throwable if the interceptors or the target object
* throws an exception
*/
@Nullable
Object invoke(@Nonnull MethodInvocation invocation) throws Throwable;
}
Invocation继承Joinpoint接口,MethodInvocation跟ConstructorInvocation继承Invocation接口,分别表示方法调用跟构造器调用
MethodInvocation的实现类会持有所有的MethodInterceptor,通过递归来模拟interceptor的拦截跟调用被拦截方法的过程。
public interface Joinpoint {
/**
* Proceed to the next interceptor in the chain.
* <p>The implementation and the semantics of this method depends
* on the actual joinpoint type (see the children interfaces).
* @return see the children interfaces' proceed definition
* @throws Throwable if the joinpoint throws an exception
*/
@Nullable
Object proceed() throws Throwable;
}
spring aop中ReflectiveMethodInvocation实现了MethodInvocation#proceed方法,组装了interceptor的调用逻辑
public Object proceed() throws Throwable {
// interceptorsAndDynamicMethodMatchers记录了所有的MethodInterceptor,
// 指针currentInterceptorIndex记录了当前正在调用哪一个interceptor,初始值为-1
// 如果已经调用完了所有的MethodInterceptor,则直接调用被拦截的方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
// InterceptorAndDynamicMethodMatcher包装了MethodInterceptor跟MethodMatcher,用来判断该拦截器是否需要拦截对应方法
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
// 如果需要拦截该方法,则调用interceptor#invoke方法,调用interceptor的逻辑。interceptor里面会再次调用proceed方法
if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
return dm.interceptor.invoke(this);
} // 否则直接调用proceed方法,跳过该interceptor
else {
return proceed();
}
}
else {
// 否则就是MethodInterceptor类型,直接调用invoke方法
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
MethodInterceptor的其中一个实现MethodBeforeAdviceInterceptor。调用完advice#before方法后,直接调用MethodInvocation#proceed方法,从而调用下一个interceptor或者直接调用方法
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {
private final MethodBeforeAdvice advice;
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
}
}
代理对象的生成
aopalliance规定了ReflectiveMethodInvocation跟MethodInterceptor,MethodInterceptor怎么在被拦截的方法中生效呢?就是代理,具体包括jdk代理跟cglib代理
AopProxy接口负责生成代理类跟代理对象,getProxy方法能够获得一个代理对象。
public interface AopProxy {
/**
* Create a new proxy object.
* <p>Uses the AopProxy's default class loader (if necessary for proxy creation):
* usually, the thread context class loader.
* @return the new proxy object (never {@code null})
* @see Thread#getContextClassLoader()
*/
Object getProxy();
/**
* Create a new proxy object.
* <p>Uses the given class loader (if necessary for proxy creation).
* {@code null} will simply be passed down and thus lead to the low-level
* proxy facility's default, which is usually different from the default chosen
* by the AopProxy implementation's {@link #getProxy()} method.
* @param classLoader the class loader to create the proxy with
* (or {@code null} for the low-level proxy facility's default)
* @return the new proxy object (never {@code null})
*/
Object getProxy(@Nullable ClassLoader classLoader);
}
AopProxy接口实现类有三个:JdkDynamicAopProxy、CglibAopProxy、ObjenesisCglibAopProxy。实际在用的就是JdkDynamicAopProxy跟ObjenesisCglibAopProxy两个。类继承结构如下
JdkDynamicAopProxy
JdkDynamicAopProxy内部持有一个AdvisedSupport,就是被代理对象的表示。JdkDynamicAopProxy还是一个InvocationHandler,所以Proxy#newProxyInstance中把this作为InvocationHandler传进去。
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
private final AdvisedSupport advised;
@Override
public Object getProxy() {
return getProxy(ClassUtils.getDefaultClassLoader());
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
}
InvocationHandler#invoke的实现
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
// 被代理的对象
TargetSource targetSource = this.advised.targetSource;
Object target = null;
// 处理equals、hashcode等方法
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 这里获取到MethodInterceptor或者InterceptorAndDynamicMethodMatcher实例
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
if (chain.isEmpty()) {
// 如果没有Interceptor则直接反射调用方法
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// 如果有Interceptor则构造一个ReflectiveMethodInvocation,调用proceed方法进行方法调用
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// Proceed to the joinpoint through the interceptor chain.
retVal = invocation.proceed();
}
// Massage return value if necessary.
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// Special case: it returned "this" and the return type of the method
// is type-compatible. Note that we can't help if the target sets
// a reference to itself in another returned object.
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// Must have come from TargetSource.
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
CglibAopProxy
类似于JdkDynamicAopProxy。CglibAopProxy就是通过Enhancer实现代理。CglibAopProxy讲MethodInterceptor逻辑放在离callbacks的第0个位置
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}
try {
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
Class<?> proxySuperClass = rootClass;
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
proxySuperClass = rootClass.getSuperclass();
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}
// Validate the class, writing log messages as necessary.
validateClassIfNecessary(proxySuperClass, classLoader);
// Configure CGLIB Enhancer...
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));
// 拿到所有的callback。第0个是处理MethodInterceptor的callback
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);
// Generate the proxy class and create a proxy instance.
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}
getCallbacks把DynamicAdvisedInterceptor放在了第0位,用来处理MethodInterceptor
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
// Parameters used for optimization choices...
boolean exposeProxy = this.advised.isExposeProxy();
boolean isFrozen = this.advised.isFrozen();
boolean isStatic = this.advised.getTargetSource().isStatic();
// Choose an "aop" interceptor (used for AOP calls).
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
// Choose a "straight to target" interceptor. (used for calls that are
// unadvised but can return this). May be required to expose the proxy.
Callback targetInterceptor;
if (exposeProxy) {
targetInterceptor = (isStatic ?
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
}
else {
targetInterceptor = (isStatic ?
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
}
// Choose a "direct to target" dispatcher (used for
// unadvised calls to static targets that cannot return this).
Callback targetDispatcher = (isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());
Callback[] mainCallbacks = new Callback[] {
aopInterceptor, // for normal advice
targetInterceptor, // invoke target without considering advice, if optimized
new SerializableNoOp(), // no override for methods mapped to this
targetDispatcher, this.advisedDispatcher,
new EqualsInterceptor(this.advised),
new HashCodeInterceptor(this.advised)
};
Callback[] callbacks;
// If the target is a static one and the advice chain is frozen,
// then we can make some optimizations by sending the AOP calls
// direct to the target using the fixed chain for that method.
if (isStatic && isFrozen) {
Method[] methods = rootClass.getMethods();
Callback[] fixedCallbacks = new Callback[methods.length];
this.fixedInterceptorMap = CollectionUtils.newHashMap(methods.length);
// TODO: small memory optimization here (can skip creation for methods with no advice)
for (int x = 0; x < methods.length; x++) {
Method method = methods[x];
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, rootClass);
fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
this.fixedInterceptorMap.put(method, x);
}
// Now copy both the callbacks from mainCallbacks
// and fixedCallbacks into the callbacks array.
callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
this.fixedInterceptorOffset = mainCallbacks.length;
}
else {
callbacks = mainCallbacks;
}
return callbacks;
}
DynamicAdvisedInterceptor是org.springframework.cglib.proxy.MethodInterceptor实现类,注意跟org.aopalliance.intercept.MethodInterceptor区分开,名字是一样的。DynamicAdvisedInterceptor#intercept方法处理了org.aopalliance.intercept.MethodInterceptor的逻辑
private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
private final AdvisedSupport advised;
public DynamicAdvisedInterceptor(AdvisedSupport advised) {
this.advised = advised;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Object target = null;
TargetSource targetSource = this.advised.getTargetSource();
try {
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target, in case it comes from a pool...
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 跟Jdk代理一样,获取到MethodInterceptor或者InterceptorAndDynamicMethodMatcher实例
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
if (chain.isEmpty() && CglibMethodInvocation.isMethodProxyCompatible(method)) {
// 如果是没有,直接反射调用方法
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = invokeMethod(target, method, argsToUse, methodProxy);
}
else {
// 否则创建CglibMethodInvocation,通过proceed进行方法调用
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
retVal = processReturnType(proxy, target, method, retVal);
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// Restore old proxy.
AopContext.setCurrentProxy(oldProxy);
}
}
}
}
ObjenesisCglibAopProxy
ObjenesisCglibAopProxy是CglibAopProxy子类。CglibAopProxy通过enhancer#create创建代理对象,这种创建方法会导致父类(被代理类)构造函数的执行,可能会导致意料之外的后果。ObjenesisCglibAopProxy通过objenesis框架创建对象,可以绕过构造函数进行对象创建
class ObjenesisCglibAopProxy extends CglibAopProxy {
private static final SpringObjenesis objenesis = new SpringObjenesis();
@Override
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
Class<?> proxyClass = enhancer.createClass();
Object proxyInstance = null;
if (objenesis.isWorthTrying()) {
try {
// 这里创建对象不会调用父类构造函数
proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
}
catch (Throwable ex) {
logger.debug("Unable to instantiate proxy using Objenesis, " +
"falling back to regular proxy construction", ex);
}
}
// 前面创建失败了,再尝试通过构造函数创建对象
if (proxyInstance == null) {
// Regular instantiation via default constructor...
try {
Constructor<?> ctor = (this.constructorArgs != null ?
proxyClass.getDeclaredConstructor(this.constructorArgTypes) :
proxyClass.getDeclaredConstructor());
ReflectionUtils.makeAccessible(ctor);
proxyInstance = (this.constructorArgs != null ?
ctor.newInstance(this.constructorArgs) : ctor.newInstance());
}
catch (Throwable ex) {
throw new AopConfigException("Unable to instantiate proxy using Objenesis, " +
"and regular proxy instantiation via default constructor fails as well", ex);
}
}
((Factory) proxyInstance).setCallbacks(callbacks);
return proxyInstance;
}
}
DefaultAopProxyFactory
DefaultAopProxyFactory通过工厂模式,根据AdvisorSupport的属性,自适应使用jdk代理或者cglib代理创建对象
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (!NativeDetector.inNativeImage() &&
(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
}
Spring aop
spring对advice接口做了很大程度的扩展,还定义了Advisor、Advised等接口。先从接口概念上看这些接口是如何组装起来的
Advice
Advisor
Advisor#getAdvice方法会返回一个Advice,即Advisor持有一个Advice
public interface Advisor {
Advice getAdvice();
}
Advisor有PointcutAdvisor和IntroductionAdvisor
PointcutAdvisor多了一个getPointcut方法
public interface PointcutAdvisor extends Advisor {
Pointcut getPointcut();
}
Pointcut有getClassFilter跟getMethodMatcher两个方法,用于判断这个这个Advisor需不需要对某个Class跟Method生效
public interface Pointcut {
ClassFilter getClassFilter();
MethodMatcher getMethodMatcher();
}
IntroductionAdvisor适用于为代理类新增接口的情况,IntroductionInfo提供新增的接口
public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
ClassFilter getClassFilter();
void validateInterfaces() throws IllegalArgumentException;
}
public interface IntroductionInfo {
Class<?>[] getInterfaces();
}
Advised
Advised代表一个要被AOP的实例,包括要被AOP的TargetSource以及一系列Advisor
public interface Advised extends TargetClassAware {
void setTargetSource(TargetSource targetSource);
TargetSource getTargetSource();
Advisor[] getAdvisors();
void addAdvisor(Advisor advisor) throws AopConfigException;
void addAdvisor(int pos, Advisor advisor) throws AopConfigException;
boolean removeAdvisor(Advisor advisor);
void removeAdvisor(int index) throws AopConfigException;
boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;
void addAdvice(Advice advice) throws AopConfigException;
void addAdvice(int pos, Advice advice) throws AopConfigException;
boolean removeAdvice(Advice advice);
}
ProxyFactory用于创建AOP代理对象,继承结构如下
ProxyFactory本身就是Advised实例,所以其本身持有了TargetSource跟Advisor。ProxyFactory#getProxy用于获取AOP代理对象。getProxy实现很简单,通过AopProxyFactory创建AopProxy,通过AopProxy创建代理对象。AopProxyFactory#createAopProxy需要一个AdvisedSupport实例,ProxyFactory将自己传了进去。AopProxyFactory#createAopProxy根据配置决定是实例化ObjenesisCglibAopProxy或者是JdkDynamicAopProxy。
public Object getProxy() {
return createAopProxy().getProxy();
}
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
ObjenesisCglibAopProxy或者是JdkDynamicAopProxy创建代理时,都会通过AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice方法获取MethodInterceptor或者是InterceptorAndDynamicMethodMatcher。AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice方法只处理了cache逻辑,具体获取逻辑交给了advisorChainFactory
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, @Nullable Class<?> targetClass) {
MethodCacheKey cacheKey = new MethodCacheKey(method);
List<Object> cached = this.methodCache.get(cacheKey);
if (cached == null) {
cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
this, method, targetClass);
this.methodCache.put(cacheKey, cached);
}
return cached;
}
advisorChainFactory是AdvisorChainFactory接口的实例,AdvisedSupport类里提供了set方法用于自定义AdvisorChainFactory。这个方法根据一个类的一个方法,获取MethodInterceptor或者InterceptorAndDynamicMethodMatcher
public interface AdvisorChainFactory {
List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, @Nullable Class<?> targetClass);
}
默认实现是DefaultAdvisorChainFactory,从advised中拿到所有的advisor,将advisor分为三种情况处理:PointcutAdvisor、IntroductionAdvisor、普通Advisor
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class<?> targetClass) {
// registry负责将Advisor转换成MethodInterceptor
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
Advisor[] advisors = config.getAdvisors();
List<Object> interceptorList = new ArrayList<>(advisors.length);
Class<?> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
Boolean hasIntroductions = null;
// 遍历所有的advisor
for (Advisor advisor : advisors) {
// 处理PointcutAdvisor
if (advisor instanceof PointcutAdvisor) {
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
// 先看类是否match,类match再看方法是否match
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
boolean match;
// 对IntroductionAwareMethodMatcher做特殊处理
if (mm instanceof IntroductionAwareMethodMatcher) {
if (hasIntroductions == null) {
hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
}
match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
}
else {
match = mm.matches(method, actualClass);
}
// 如果match,再看MethodMatcher是否是运行时的(是否需要在运行时动态判断match与否)。如果需要,则将
// MethodInterceptor包装成InterceptorAndDynamicMethodMatcher;否则直接放到interceptorList
if (match) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
if (mm.isRuntime()) {
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
// 处理IntroductionAdvisor。只看一下类是否match。match则获取Interceptor,加入interceptorList
else if (advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
// 对于普通的Advisor。直接获取Interceptor,加入interceptorList
else {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
return interceptorList;
}
DefaultAdvisorChainFactory里面使用了AdvisorAdapterRegistry,将Advisor转换成MethodInterceptor。AdvisorAdapterRegistry默认实现是DefaultAdvisorAdapterRegistry。DefaultAdvisorAdapterRegistry默认有三个AdvisorAdapter:MethodBeforeAdviceAdapter、AfterReturningAdviceAdapter、ThrowsAdviceAdapter。也可以通过registerAdvisorAdapter方法添加Adaptor
public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {
private final List<AdvisorAdapter> adapters = new ArrayList<>(3);
public DefaultAdvisorAdapterRegistry() {
registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
registerAdvisorAdapter(new AfterReturningAdviceAdapter());
registerAdvisorAdapter(new ThrowsAdviceAdapter());
}
public void registerAdvisorAdapter(AdvisorAdapter adapter) {
this.adapters.add(adapter);
}
}
AdvisorAdapterRegistry#getInterceptors将Advisor转换成MethodInterceptor。getInterceptors从Advisor里取出Advice,实际的转换委托给AdvisorAdapter
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
List<MethodInterceptor> interceptors = new ArrayList<>(3);
Advice advice = advisor.getAdvice();
if (advice instanceof MethodInterceptor) {
interceptors.add((MethodInterceptor) advice);
}
for (AdvisorAdapter adapter : this.adapters) {
if (adapter.supportsAdvice(advice)) {
interceptors.add(adapter.getInterceptor(advisor));
}
}
if (interceptors.isEmpty()) {
throw new UnknownAdviceTypeException(advisor.getAdvice());
}
return interceptors.toArray(new MethodInterceptor[0]);
}
AdvisorAdapter接口有两个方法,supportsAdvice跟getInterceptor。实现类有MethodBeforeAdviceAdapter、AfterReturningAdviceAdapter、ThrowsAdviceAdapter。分别看下具体实现
public interface AdvisorAdapter {
boolean supportsAdvice(Advice advice);
MethodInterceptor getInterceptor(Advisor advisor);
}
MethodBeforeAdviceAdapter#getInterceptor返回了一个MethodBeforeAdviceInterceptor
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof MethodBeforeAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}
MethodBeforeAdviceInterceptor
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, BeforeAdvice, Serializable {
private final MethodBeforeAdvice advice;
public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
}
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
// 先调用advice#before,然后mi#proceed调用下一个Interceptor
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
return mi.proceed();
}
}
AfterReturningAdviceAdapter跟MethodBeforeAdviceAdapter实现基本一样。
ThrowsAdviceAdapter跟前面类似,返回了ThrowsAdviceInterceptor。但ThrowsAdviceInterceptor实现跟前面不一样
class ThrowsAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return (advice instanceof ThrowsAdvice);
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
return new ThrowsAdviceInterceptor(advisor.getAdvice());
}
}
ThrowsAdvice是个标签接口,本身没有方法。拦截方法是根据约定来的,支持两类拦截方法
// 名称为afterThrowing,只有一个参数,类型为XXXException。可以有多个重载
public void afterThrowing(XXXException ex);
// 名称为afterThrowing,有四个参数,前面三个参数类型固定,最后一个参数类型为类型为XXXException。也可以有多个重载
public void afterThrowing(Method method, Object[] args, Object target, XXXException ex);
ThrowsAdviceInterceptor在构造函数里对这个throwsAdvice做了解析,提取出所有afterThrowing方法,存到exceptionHandlerMap里
public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
private static final String AFTER_THROWING = "afterThrowing";
private final Object throwsAdvice;
private final Map<Class<?>, Method> exceptionHandlerMap = new HashMap<>();
public ThrowsAdviceInterceptor(Object throwsAdvice) {
Assert.notNull(throwsAdvice, "Advice must not be null");
this.throwsAdvice = throwsAdvice;
Method[] methods = throwsAdvice.getClass().getMethods();
// 遍历throwsAdvice里的所有方法
for (Method method : methods) {
// 方法名为afterThrowing,且参数个数为1或4
if (method.getName().equals(AFTER_THROWING) &&
(method.getParameterCount() == 1 || method.getParameterCount() == 4)) {
// 拿到异常类型
Class<?> throwableParam = method.getParameterTypes()[method.getParameterCount() - 1];
if (Throwable.class.isAssignableFrom(throwableParam)) {
// 将异常作为key、method作为value存入exceptionHandlerMap
this.exceptionHandlerMap.put(throwableParam, method);
}
}
}
}
}
ThrowsAdviceInterceptor#invoke方法,当有异常抛出时,会从exceptionHandlerMap查找处理的方法,然后反射调用handler,最后再抛出异常
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
catch (Throwable ex) {
Method handlerMethod = getExceptionHandler(ex);
if (handlerMethod != null) {
invokeHandlerMethod(mi, ex, handlerMethod);
}
throw ex;
}
}
private Method getExceptionHandler(Throwable exception) {
Class<?> exceptionClass = exception.getClass();
Method handler = this.exceptionHandlerMap.get(exceptionClass);
// 这里会按照异常的类继承结构去查找
while (handler == null && exceptionClass != Throwable.class) {
exceptionClass = exceptionClass.getSuperclass();
handler = this.exceptionHandlerMap.get(exceptionClass);
}
return handler;
}
// 这里就是反射调用了
private void invokeHandlerMethod(MethodInvocation mi, Throwable ex, Method method) throws Throwable {
Object[] handlerArgs;
if (method.getParameterCount() == 1) {
handlerArgs = new Object[] {ex};
}
else {
handlerArgs = new Object[] {mi.getMethod(), mi.getArguments(), mi.getThis(), ex};
}
try {
method.invoke(this.throwsAdvice, handlerArgs);
}
catch (InvocationTargetException targetEx) {
throw targetEx.getTargetException();
}
}
ProxyCreator
前面ProxyFactory根据已有的TargetSource跟Advisor去创建代理对象,但是TargetSource跟Advisor怎么来?什么时期创建代理对象?这些问题ProxyCreator来解决
AbstractAutoProxyCreator
AbstractAutoProxyCreator实现了SmartInstantiationAwareBeanPostProcessor,在bean的实例化之前跟实例化之后都会对bean做处理。AbstractAutoProxyCreator处理了代理对象创建的逻辑,对于Advisor从哪里来则交给子类去实现。
bean实例化之前创建代理对象(通过自定义TargetSource绕过被代理bean的创建)
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;
}
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
// getCustomTargetSource获取自定义的TargetSource。如果能获取到则不会去实例化这个bean,而对自定义的
// TargetSource进行AOP代理
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
// 先通过getAdvicesAndAdvisorsForBean拿到Advices或者Advisors,通过createProxy创建代理对象
// getAdvicesAndAdvisorsForBean是一个抽象方法,由子类实现
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
return null;
}
getCustomTargetSource就是遍历customTargetSourceCreators来创建TargetSource。AbstractAutoProxyCreator提供了set方法来自定义customTargetSourceCreators
protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
if (this.customTargetSourceCreators != null &&
this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
TargetSource ts = tsc.getTargetSource(beanClass, beanName);
if (ts != null) {
return ts;
}
}
}
// No custom TargetSource found.
return null;
}
bean实例化之后创建代理对象
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;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
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;
}
// 如果能够找到Advice或者Advisor,就将bean包装成SingletonTargetSource,然后通过createProxy创建代理对象
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;
}
getAdvicesAndAdvisorsForBean是一个抽象方法,由子类实现。AbstractAutoProxyCreator实现了createProxy方法创建代理对象
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
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);
if (proxyFactory.isProxyTargetClass()) {
if (Proxy.isProxyClass(beanClass) || ClassUtils.isLambdaClass(beanClass)) {
for (Class<?> ifc : beanClass.getInterfaces()) {
proxyFactory.addInterface(ifc);
}
}
}
else {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}
// specificInterceptors里面包含Advice或者Advisor,要将Advice转成Advisor。并且还要添加上commonInterceptors
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
// 设置Advisor
proxyFactory.addAdvisors(advisors);
// 设置targetSource
proxyFactory.setTargetSource(targetSource);
// 自定义操作,空实现。由子类覆盖
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
ClassLoader classLoader = getProxyClassLoader();
if (classLoader instanceof SmartClassLoader && classLoader != beanClass.getClassLoader()) {
classLoader = ((SmartClassLoader) classLoader).getOriginalClassLoader();
}
// 创建代理对象
return proxyFactory.getProxy(classLoader);
}
AbstractAdvisorAutoProxyCreator
AbstractAdvisorAutoProxyCreator继承AbstractAutoProxyCreator,实现了getAdvicesAndAdvisorsForBean方法,这个实现只返回了Advisor。getAdvicesAndAdvisorsForBean调用findEligibleAdvisors查找Advisor
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();
}
findEligibleAdvisors是个模板方法。有四个步骤
1、findCandidateAdvisors查找可能的Advisor
2、findAdvisorsThatCanApply过滤掉不能用在当前bean上的Advisor
3、extendAdvisor做自定义扩展。默认空实现
4、sortAdvisors对Advisor排序。默认使用AnnotationAwareOrderComparator#sort排序
InfrastructureAdvisorAutoProxyCreator、AspectJAwareAdvisorAutoProxyCreator、AnnotationAwareAspectJAutoProxyCreator也就是重写了这几个模板方法
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
List<Advisor> candidateAdvisors = findCandidateAdvisors();
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
AbstractAdvisorAutoProxyCreator提供了这几个方法的默认实现
findCandidateAdvisors将查找工作委托给advisorRetrievalHelper。AnnotationAwareAspectJAutoProxyCreator重写了这个方法
protected List<Advisor> findCandidateAdvisors() {
return this.advisorRetrievalHelper.findAdvisorBeans();
}
advisorRetrievalHelper是BeanFactoryAdvisorRetrievalHelperAdapter实例。BeanFactoryAdvisorRetrievalHelperAdapter是AbstractAdvisorAutoProxyCreator的一个内部类,继承BeanFactoryAdvisorRetrievalHelper类,并覆盖了isEligibleBean方法,isEligibleBean方法调用了AbstractAdvisorAutoProxyCreator#isEligibleAdvisorBean方法。 isEligibleAdvisorBean默认返回true,InfrastructureAdvisorAutoProxyCreator类覆盖了isEligibleAdvisorBean方法
private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper {
public BeanFactoryAdvisorRetrievalHelperAdapter(ConfigurableListableBeanFactory beanFactory) {
super(beanFactory);
}
@Override
protected boolean isEligibleBean(String beanName) {
return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName);
}
}
BeanFactoryAdvisorRetrievalHelper#findAdvisorBeans方法
public List<Advisor> findAdvisorBeans() {
// 通过BeanFactoryUtils#beanNamesForTypeIncludingAncestors方法从beanFactory获取Advisor bean,
// 缓存到cachedAdvisorBeanNames
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
this.cachedAdvisorBeanNames = advisorNames;
}
if (advisorNames.length == 0) {
return new ArrayList<>();
}
List<Advisor> advisors = new ArrayList<>();
// 遍历advisorNames
for (String name : advisorNames) {
// isEligibleBean默认true,由子类覆盖
if (isEligibleBean(name)) {
if (this.beanFactory.isCurrentlyInCreation(name)) {
//如果正在创建这个bean,忽略这个bean
}
else {
try {
// 从beanfactory获取bean,加入advisors
advisors.add(this.beanFactory.getBean(name, Advisor.class));
}
catch (BeanCreationException ex) {
// handle ex
throw ex;
}
}
}
}
return advisors;
}
findAdvisorsThatCanApply方法调用AopUtils#findAdvisorsThatCanApply来过滤Advisor
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null);
}
}
AopUtils#findAdvisorsThatCanApply先处理IntroductionAdvisor,后处理其他Advisor(此时能够知道有没有IntroductionAdvisor,方便给IntroductionAwareMethodMatcher传参)。对于IntroductionAdvisor,拿到其ClassFilter,看跟targetClass是否match;对于PointcutAdvisor,先看class是否match,再看是否有match的方法;对于其他Advisor,默认都match
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}
List<Advisor> eligibleAdvisors = new ArrayList<>();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}
InfrastructureAdvisorAutoProxyCreator
InfrastructureAdvisorAutoProxyCreator继承AbstractAdvisorAutoProxyCreator,只覆盖了isEligibleAdvisorBean方法,如果Advisor的role=ROLE_INFRASTRUCTURE才返回true。该方法被父类AbstractAdvisorAutoProxyCreator里面的BeanFactoryAdvisorRetrievalHelperAdapter#isEligibleBean调用
public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
@Override
protected boolean isEligibleAdvisorBean(String beanName) {
return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) &&
this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
}
}
AspectJAwareAdvisorAutoProxyCreator
AspectJAwareAdvisorAutoProxyCreator继承AbstractAdvisorAutoProxyCreator类,重写了sortAdvisors方法跟extendAdvisors方法
extendAdvisors就是调用了AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary处理了一下candidateAdvisors
protected void extendAdvisors(List<Advisor> candidateAdvisors) {
AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(candidateAdvisors);
}
AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary就是判断了一下advisors里有没有AspectJAdvisor,如果有则在adivisors第一个加一个ExposeInvocationInterceptor.ADVISOR
public static boolean makeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) {
if (!advisors.isEmpty()) {
boolean foundAspectJAdvice = false;
for (Advisor advisor : advisors) {
if (isAspectJAdvice(advisor)) {
foundAspectJAdvice = true;
break;
}
}
if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) {
advisors.add(0, ExposeInvocationInterceptor.ADVISOR);
return true;
}
}
return false;
}
ExposeInvocationInterceptor有什么作用呢?ExposeInvocationInterceptor将当前MethodInvocation保存到threadLocal里,是的AspectJAdvice能够获取到当前的MethodInvocation
public final class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable {
// 单例对象
public static final ExposeInvocationInterceptor INSTANCE = new ExposeInvocationInterceptor();
public static final Advisor ADVISOR = new DefaultPointcutAdvisor(INSTANCE) {
@Override
public String toString() {
return ExposeInvocationInterceptor.class.getName() +".ADVISOR";
}
};
private static final ThreadLocal<MethodInvocation> invocation =
new NamedThreadLocal<>("Current AOP method invocation");
public static MethodInvocation currentInvocation() throws IllegalStateException {
// currentInvocation提供当前methodInvocation的查询
MethodInvocation mi = invocation.get();
if (mi == null) {
throw new IllegalStateException(
"No MethodInvocation found: Check that an AOP invocation is in progress and that the " +
"ExposeInvocationInterceptor is upfront in the interceptor chain. Specifically, note that " +
"advices with order HIGHEST_PRECEDENCE will execute before ExposeInvocationInterceptor! " +
"In addition, ExposeInvocationInterceptor and ExposeInvocationInterceptor.currentInvocation() " +
"must be invoked from the same thread.");
}
return mi;
}
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {
// invoke方法将当前的MethodInvocation保存到threadLocal里
MethodInvocation oldInvocation = invocation.get();
invocation.set(mi);
try {
return mi.proceed();
}
finally {
invocation.set(oldInvocation);
}
}
}
AnnotationAwareAspectJAutoProxyCreator
AnnotationAwareAspectJAutoProxyCreator继承AspectJAwareAdvisorAutoProxyCreator,增加对AspectJ注解的支持
AnnotationAwareAspectJAutoProxyCreator重新了findCandidateAdvisors方法。在父类查找Advisor的基础上,增加了按照aspectJAdvisorsBuilder查找Advisor的逻辑
protected List<Advisor> findCandidateAdvisors() {
List<Advisor> advisors = super.findCandidateAdvisors();
if (this.aspectJAdvisorsBuilder != null) {
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
aspectJAdvisorsBuilder是AnnotationAwareAspectJAutoProxyCreator的内部类BeanFactoryAspectJAdvisorsBuilderAdapter,是在initBeanFactory初始化过程创建的
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.initBeanFactory(beanFactory);
if (this.aspectJAdvisorFactory == null) {
this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
}
this.aspectJAdvisorsBuilder =
new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
}
BeanFactoryAspectJAdvisorsBuilderAdapter#buildAspectJAdvisors方法会获取到aspcetj相关的advisor
public List<Advisor> buildAspectJAdvisors() {
// aspectBeanNames是个缓存。表示有@Aspect注解的bean
List<String> aspectNames = this.aspectBeanNames;
// 双重校验所初始化aspectBeanNames
if (aspectNames == null) {
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new ArrayList<>();
aspectNames = new ArrayList<>();
// 从beanfactory获取所有的bean
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Object.class, true, false);
for (String beanName : beanNames) {
// isEligibleBean默认返回true,BeanFactoryAspectJAdvisorsBuilderAdapter覆盖了这个方法,
// 里面调用AnnotationAwareAspectJAutoProxyCreator#isEligibleAspectBean,该方法根据
// includePatterns判断是否isEligibleBean
if (!isEligibleBean(beanName)) {
continue;
}
Class<?> beanType = this.beanFactory.getType(beanName, false);
if (beanType == null) {
continue;
}
// isAspect判断这个bean的类上面有没有@Aspect注解
if (this.advisorFactory.isAspect(beanType)) {
aspectNames.add(beanName);
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
// 如果代理advisor是单例的,创建MetadataAwareAspectInstanceFactory,通过advisorFactory
// 获取Advisor
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
// 如果bean是单例的,那么这些advisor可以缓存下来,下次使用;如果不是单例的,就只缓存factory
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors);
}
else {
this.aspectFactoryCache.put(beanName, factory);
}
advisors.addAll(classAdvisors);
}
else {
// 非单例情况,advisor获取逻辑同上,缓存逻辑不同
if (this.beanFactory.isSingleton(beanName)) {
throw new IllegalArgumentException("Bean with name '" + beanName +
"' is a singleton, but aspect instantiation model is not singleton");
}
MetadataAwareAspectInstanceFactory factory =
new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
this.aspectFactoryCache.put(beanName, factory);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
}
this.aspectBeanNames = aspectNames;
return advisors;
}
}
}
if (aspectNames.isEmpty()) {
return Collections.emptyList();
}
// aspectNames已经初始化过。直接从缓存中拿Advisor或者MetadataAwareAspectInstanceFactory
List<Advisor> advisors = new ArrayList<>();
for (String aspectName : aspectNames) {
List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
if (cachedAdvisors != null) {
advisors.addAll(cachedAdvisors);
}
else {
MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
advisors.addAll(this.advisorFactory.getAdvisors(factory));
}
}
return advisors;
}
自动配置
ProxyCreator负责从beanFactory中获取Advisor,通过BeanPostProcessor生命周期回调接口对bean进行aop代理,就需要配置类将ProxyCreator注册到BeanFactory中。由于ProxyCreator只需要一个,所以AopConfigUtils提供了多个ProxyCreator的优先级控制跟注册工具函数
public abstract class AopConfigUtils {
// proxyCreatory的beanName
public static final String AUTO_PROXY_CREATOR_BEAN_NAME =
"org.springframework.aop.config.internalAutoProxyCreator";
// 包含InfrastructureAdvisorAutoProxyCreator、AspectJAwareAdvisorAutoProxyCreator、
// AnnotationAwareAspectJAutoProxyCreator,优先级递增。
private static final List<Class<?>> APC_PRIORITY_LIST = new ArrayList<>(3);
static {
APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
}
// cls就是上面三个类名字,如果是这三个以外,findPriorityForClass会抛异常
private static BeanDefinition registerOrEscalateApcAsRequired(
Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {
// 如果已经有这个bean了,则比较优先级,然后替换。优先级就是cls在APC_PRIORITY_LIST中的序号,序号越大优先级越高
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
int requiredPriority = findPriorityForClass(cls);
if (currentPriority < requiredPriority) {
apcDefinition.setBeanClassName(cls.getName());
}
}
return null;
}
// bean不存在,则直接注册这个bean
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
return beanDefinition;
}
}
AspectJ
AnnotationAwareAspectJAutoProxyCreator提供了对AspectJ注解的支持。是通过在ReflectiveAspectJAdvisorFactory#getAdvisors方法中处理bean里面的AspectJ相关注解,返回Advisor实现的。