切面觸發過程
/**
* 通知鏈工廠
*/
public interface AdvisorChainFactory {
/**
* 基於指定的 Advised 配置生成 org.aopalliance.intercept.MethodInterceptor 鏈
*/
List<Object> getInterceptorsAndDynamicInterceptionAdvice(Advised config, Method method, @Nullable Class<?> targetClass);
}
@SuppressWarnings("serial")
public class DefaultAdvisorChainFactory implements AdvisorChainFactory, Serializable {
@Override
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class<?> targetClass) {
// Advisor 適配器註冊中心
final AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
// 獲取所有配置的 Advisor
final Advisor[] advisors = config.getAdvisors();
final List<Object> interceptorList = new ArrayList<>(advisors.length);
// 讀取目標類型
final Class<?> actualClass = targetClass != null ? targetClass : method.getDeclaringClass();
Boolean hasIntroductions = null;
for (final Advisor advisor : advisors) {
// 1)PointcutAdvisor
if (advisor instanceof PointcutAdvisor) {
final PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
final MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
boolean match;
if (mm instanceof IntroductionAwareMethodMatcher) {
if (hasIntroductions == null) {
hasIntroductions = hasMatchingIntroductions(advisors, actualClass);
}
match = ((IntroductionAwareMethodMatcher) mm).matches(method, actualClass, hasIntroductions);
}
else {
match = mm.matches(method, actualClass);
}
// 如果匹配目標方法
if (match) {
// 讀取 MethodInterceptor
final MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
if (mm.isRuntime()) {
// 如果方法匹配器是動態的,將 MethodInterceptor 和 MethodMatcher 封裝後加入攔截器鏈
for (final MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
// 2)IntroductionAdvisor
else if (advisor instanceof IntroductionAdvisor) {
final IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
final Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
// 3)其他 Advisor【無內置實現】
else {
final Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
return interceptorList;
}
/**
* Advisor 鏈匹配方法引入
*/
private static boolean hasMatchingIntroductions(Advisor[] advisors, Class<?> actualClass) {
for (final Advisor advisor : advisors) {
if (advisor instanceof IntroductionAdvisor) {
final IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (ia.getClassFilter().matches(actualClass)) {
return true;
}
}
}
return false;
}
}
@SuppressWarnings("serial")
public class DefaultAdvisorAdapterRegistry implements AdvisorAdapterRegistry, Serializable {
/**
* Advisor 適配器
*/
private final List<AdvisorAdapter> adapters = new ArrayList<>(3);
/**
* Create a new DefaultAdvisorAdapterRegistry, registering well-known adapters.
*/
public DefaultAdvisorAdapterRegistry() {
registerAdvisorAdapter(new MethodBeforeAdviceAdapter());
registerAdvisorAdapter(new AfterReturningAdviceAdapter());
registerAdvisorAdapter(new ThrowsAdviceAdapter());
}
@Override
public Advisor wrap(Object adviceObject) throws UnknownAdviceTypeException {
// 本身就是 Advisor
if (adviceObject instanceof Advisor) {
return (Advisor) adviceObject;
}
if (!(adviceObject instanceof Advice)) {
throw new UnknownAdviceTypeException(adviceObject);
}
final Advice advice = (Advice) adviceObject;
if (advice instanceof MethodInterceptor) {
// 本身是一個 MethodInterceptor
return new DefaultPointcutAdvisor(advice);
}
for (final AdvisorAdapter adapter : adapters) {
// 本身不是 MethodInterceptor && Advisor 支持此 Advice
if (adapter.supportsAdvice(advice)) {
return new DefaultPointcutAdvisor(advice);
}
}
throw new UnknownAdviceTypeException(advice);
}
@Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
// 將目標 Advisor 的所有通知適配爲 MethodInterceptor
final List<MethodInterceptor> interceptors = new ArrayList<>(3);
final Advice advice = advisor.getAdvice();
if (advice instanceof MethodInterceptor) {
interceptors.add((MethodInterceptor) advice);
}
for (final AdvisorAdapter adapter : adapters) {
// 如果目標適配器支持此 advice && 將其適配爲 MethodInterceptor
if (adapter.supportsAdvice(advice)) {
interceptors.add(adapter.getInterceptor(advisor));
}
}
if (interceptors.isEmpty()) {
throw new UnknownAdviceTypeException(advisor.getAdvice());
}
return interceptors.toArray(new MethodInterceptor[0]);
}
@Override
public void registerAdvisorAdapter(AdvisorAdapter adapter) {
adapters.add(adapter);
}
}
/**
* 將 MethodBeforeAdvice 適配爲 MethodInterceptor
*/
@SuppressWarnings("serial")
class MethodBeforeAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return advice instanceof MethodBeforeAdvice;
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
final MethodBeforeAdvice advice = (MethodBeforeAdvice) advisor.getAdvice();
return new MethodBeforeAdviceInterceptor(advice);
}
}
@SuppressWarnings("serial")
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
public Object invoke(MethodInvocation mi) throws Throwable {
// 執行前置通知
advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
// 執行攔截連中的下一個攔截器
return mi.proceed();
}
}
/**
* 將 AfterReturningAdvice 適配爲 MethodInterceptor
*/
@SuppressWarnings("serial")
class AfterReturningAdviceAdapter implements AdvisorAdapter, Serializable {
@Override
public boolean supportsAdvice(Advice advice) {
return advice instanceof AfterReturningAdvice;
}
@Override
public MethodInterceptor getInterceptor(Advisor advisor) {
final AfterReturningAdvice advice = (AfterReturningAdvice) advisor.getAdvice();
return new AfterReturningAdviceInterceptor(advice);
}
}
@SuppressWarnings("serial")
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
private final AfterReturningAdvice advice;
public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
// 執行下一個攔截器
final Object retVal = mi.proceed();
// 執行方法返回通知
advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
return retVal;
}
}
/**
* 將 ThrowsAdvice 適配爲 MethodInterceptor
*/
@SuppressWarnings("serial")
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());
}
}
public class ThrowsAdviceInterceptor implements MethodInterceptor, AfterAdvice {
private static final String AFTER_THROWING = "afterThrowing";
private static final Log logger = LogFactory.getLog(ThrowsAdviceInterceptor.class);
private final Object throwsAdvice;
/** Methods on throws advice, keyed by exception class. */
private final Map<Class<?>, Method> exceptionHandlerMap = new HashMap<>();
public ThrowsAdviceInterceptor(Object throwsAdvice) {
Assert.notNull(throwsAdvice, "Advice must not be null");
this.throwsAdvice = throwsAdvice;
final Method[] methods = throwsAdvice.getClass().getMethods();
for (final Method method : methods) {
/**
* 查找 1 個參數 public void afterThrowing(Exception ex)
* 或 4 個參數 public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
* 的指定格式的異常處理器
*/
if (method.getName().equals(AFTER_THROWING) &&
(method.getParameterCount() == 1 || method.getParameterCount() == 4)) {
final Class<?> throwableParam = method.getParameterTypes()[method.getParameterCount() - 1];
if (Throwable.class.isAssignableFrom(throwableParam)) {
// 註冊異常處理器
exceptionHandlerMap.put(throwableParam, method);
if (logger.isDebugEnabled()) {
logger.debug("Found exception handler method on throws advice: " + method);
}
}
}
}
if (exceptionHandlerMap.isEmpty()) {
throw new IllegalArgumentException(
"At least one handler method must be found in class [" + throwsAdvice.getClass() + "]");
}
}
public int getHandlerMethodCount() {
return exceptionHandlerMap.size();
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
catch (final Throwable ex) {
final Method handlerMethod = getExceptionHandler(ex);
if (handlerMethod != null) {
// 觸發異常處理器
invokeHandlerMethod(mi, ex, handlerMethod);
}
throw ex;
}
}
@Nullable
private Method getExceptionHandler(Throwable exception) {
Class<?> exceptionClass = exception.getClass();
if (logger.isTraceEnabled()) {
logger.trace("Trying to find handler for exception of type [" + exceptionClass.getName() + "]");
}
Method handler = exceptionHandlerMap.get(exceptionClass);
while (handler == null && exceptionClass != Throwable.class) {
exceptionClass = exceptionClass.getSuperclass();
handler = exceptionHandlerMap.get(exceptionClass);
}
if (handler != null && logger.isTraceEnabled()) {
logger.trace("Found handler for exception of type [" + exceptionClass.getName() + "]: " + handler);
}
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(throwsAdvice, handlerArgs);
}
catch (final InvocationTargetException targetEx) {
throw targetEx.getTargetException();
}
}
}
- 構建 ReflectiveMethodInvocation 觸發通知鏈和切點方法調用
public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
/**
* 代理對象
*/
protected final Object proxy;
/**
* 目標對象
*/
@Nullable
protected final Object target;
/**
* 目標方法
*/
protected final Method method;
/**
* 參數數組
*/
protected Object[] arguments = new Object[0];
/**
* 目標類型
*/
@Nullable
private final Class<?> targetClass;
/**
* 用戶特定屬性
*/
@Nullable
private Map<String, Object> userAttributes;
/**
* List of MethodInterceptor and InterceptorAndDynamicMethodMatcher
* that need dynamic checks.
*/
protected final List<?> interceptorsAndDynamicMethodMatchers;
/**
* 當前執行的目標攔截器索引
*/
private int currentInterceptorIndex = -1;
protected ReflectiveMethodInvocation(
Object proxy, @Nullable Object target, Method method, @Nullable Object[] arguments,
@Nullable Class<?> targetClass, List<Object> interceptorsAndDynamicMethodMatchers) {
this.proxy = proxy;
this.target = target;
this.targetClass = targetClass;
this.method = BridgeMethodResolver.findBridgedMethod(method);
this.arguments = AopProxyUtils.adaptArgumentsIfNecessary(method, arguments);
this.interceptorsAndDynamicMethodMatchers = interceptorsAndDynamicMethodMatchers;
}
@Override
public final Object getProxy() {
return proxy;
}
@Override
@Nullable
public final Object getThis() {
return target;
}
@Override
public final AccessibleObject getStaticPart() {
return method;
}
@Override
public final Method getMethod() {
return method;
}
@Override
public final Object[] getArguments() {
return arguments;
}
@Override
public void setArguments(Object... arguments) {
this.arguments = arguments;
}
@Override
@Nullable
public Object proceed() throws Throwable {
// 所有的攔截器都已經執行完畢,則執行目標方法
if (currentInterceptorIndex == interceptorsAndDynamicMethodMatchers.size() - 1) {
return invokeJoinpoint();
}
// 獲取指定索引處的攔截器
final Object interceptorOrInterceptionAdvice =
interceptorsAndDynamicMethodMatchers.get(++currentInterceptorIndex);
// 1)如果是動態匹配執行
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
final InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
final Class<?> targetClass = this.targetClass != null ? this.targetClass : method.getDeclaringClass();
// 如果匹配,則執行當前的攔截器
if (dm.methodMatcher.matches(method, targetClass, arguments)) {
return dm.interceptor.invoke(this);
}
else {
// 直接執行下一個攔截器
return proceed();
}
}
else {
// 2)執行此攔截器
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
/**
* 通過反射的方式執行切入點方法
*/
@Nullable
protected Object invokeJoinpoint() throws Throwable {
return AopUtils.invokeJoinpointUsingReflection(target, method, arguments);
}
@Override
public MethodInvocation invocableClone() {
Object[] cloneArguments = arguments;
if (arguments.length > 0) {
// Build an independent copy of the arguments array.
cloneArguments = new Object[arguments.length];
System.arraycopy(arguments, 0, cloneArguments, 0, arguments.length);
}
return invocableClone(cloneArguments);
}
@Override
public MethodInvocation invocableClone(Object... arguments) {
if (userAttributes == null) {
userAttributes = new HashMap<>();
}
// Create the MethodInvocation clone.
try {
final ReflectiveMethodInvocation clone = (ReflectiveMethodInvocation) clone();
clone.arguments = arguments;
return clone;
}
catch (final CloneNotSupportedException ex) {
throw new IllegalStateException(
"Should be able to clone object of type [" + getClass() + "]: " + ex);
}
}
@Override
public void setUserAttribute(String key, @Nullable Object value) {
if (value != null) {
if (userAttributes == null) {
userAttributes = new HashMap<>();
}
userAttributes.put(key, value);
}
else {
if (userAttributes != null) {
userAttributes.remove(key);
}
}
}
@Override
@Nullable
public Object getUserAttribute(String key) {
return userAttributes != null ? userAttributes.get(key) : null;
}
public Map<String, Object> getUserAttributes() {
if (userAttributes == null) {
userAttributes = new HashMap<>();
}
return userAttributes;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ReflectiveMethodInvocation: ");
sb.append(method).append("; ");
if (target == null) {
sb.append("target is null");
}
else {
sb.append("target is of class [").append(target.getClass().getName()).append(']');
}
return sb.toString();
}
}
@SuppressWarnings("serial")
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
public Object invoke(MethodInvocation mi) throws Throwable {
// 執行前置通知
advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
// 執行攔截連中的下一個攔截器
return mi.proceed();
}
}
@SuppressWarnings("serial")
public class AspectJAroundAdvice extends AbstractAspectJAdvice implements MethodInterceptor, Serializable {
public AspectJAroundAdvice(
Method aspectJAroundAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {
super(aspectJAroundAdviceMethod, pointcut, aif);
}
@Override
public boolean isBeforeAdvice() {
return false;
}
@Override
public boolean isAfterAdvice() {
return false;
}
@Override
protected boolean supportsProceedingJoinPoint() {
return true;
}
/**
* 執行目標方法
*/
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
if (!(mi instanceof ProxyMethodInvocation)) {
throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
}
final ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;
final ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi);
final JoinPointMatch jpm = getJoinPointMatch(pmi);
return invokeAdviceMethod(pjp, jpm, null, null);
}
/**
* Return the ProceedingJoinPoint for the current invocation,
*/
protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) {
return new MethodInvocationProceedingJoinPoint(rmi);
}
}
@SuppressWarnings("serial")
public class AfterReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice, Serializable {
private final AfterReturningAdvice advice;
/**
* Create a new AfterReturningAdviceInterceptor for the given advice.
* @param advice the AfterReturningAdvice to wrap
*/
public AfterReturningAdviceInterceptor(AfterReturningAdvice advice) {
Assert.notNull(advice, "Advice must not be null");
this.advice = advice;
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
Object retVal = mi.proceed();
this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
return retVal;
}
}
@SuppressWarnings("serial")
public class AspectJAfterThrowingAdvice extends AbstractAspectJAdvice
implements MethodInterceptor, AfterAdvice, Serializable {
public AspectJAfterThrowingAdvice(
Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {
super(aspectJBeforeAdviceMethod, pointcut, aif);
}
@Override
public boolean isBeforeAdvice() {
return false;
}
@Override
public boolean isAfterAdvice() {
return true;
}
@Override
public void setThrowingName(String name) {
setThrowingNameNoCheck(name);
}
/**
* 執行目標方法
*/
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
catch (final Throwable ex) {
// 是否需要執行異常通知
if (shouldInvokeOnThrowing(ex)) {
invokeAdviceMethod(getJoinPointMatch(), null, ex);
}
throw ex;
}
}
/**
* 異常類型是否和通知方法中的參數匹配
*/
private boolean shouldInvokeOnThrowing(Throwable ex) {
return getDiscoveredThrowingType().isAssignableFrom(ex.getClass());
}
}
@SuppressWarnings("serial")
public class AspectJAfterAdvice extends AbstractAspectJAdvice
implements MethodInterceptor, AfterAdvice, Serializable {
public AspectJAfterAdvice(
Method aspectJBeforeAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) {
super(aspectJBeforeAdviceMethod, pointcut, aif);
}
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
// 執行目標方法
return mi.proceed();
}
finally {
invokeAdviceMethod(getJoinPointMatch(), null, null);
}
}
@Override
public boolean isBeforeAdvice() {
return false;
}
@Override
public boolean isAfterAdvice() {
return true;
}
}