上篇博文中涉及到两个很重要的注解,EnableAop 和InterceptorAdvice 具体的定义如下
package com.annotations;
import org.aopalliance.aop.Advice;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by zoujianglin
* 2018/8/29 0029.
* <p>
* 这仅仅是一个标志性注解,使用该注解意味着
* 你将对该类实现动态代理,启动aop功能,具体需要
* 配合{@link InterceptorAdvice} 使用,如果你给EnableAop
* 的advices赋值,那么它将对该类的所有方法生效,(除了object自带的方法以外)
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableAop {
Class<? extends Advice>[] advices() default {};
}
package com.annotations;
import org.aopalliance.aop.Advice;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by zoujianglin
* 2018/8/29 0029.
* 该注解作用于方法上,标志着某个类的方法
* 将被代理,advices()将返回该方法上的拦截器
* 并且,使用该注解时你必须配合{@link EnableAop} 才可以
* 正常工作
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InterceptorAdvice {
Class<? extends Advice>[] advices() ;
}
另外也涉及到了两个重要的类
MyMethodBeforeAdvice 和 MyAfterReturnAdvice 两类的继承结构图如下
具体实现如下所示
Advice:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.aopalliance.aop;
public interface Advice {
}
AfterReturningAdice 定义如下 相当于aop中的后置通知,在方法调用返回后,将会被调用
package com.autoproxy.Adapter;
import org.aopalliance.aop.Advice;
import java.lang.reflect.Method;
/**
* Created by zoujianglin
* 2018/8/29 0029.
*/
public interface AfterReturningAdice extends Advice {
void after(Method method, Object[] args, Object target) throws Throwable;
}
MethodBeforeAdvice 定义如下 相当于springAop中的后置通知,在方法调用之前将会被调用
package com.autoproxy.Adapter;
import org.aopalliance.aop.Advice;
import java.lang.reflect.Method;
/**
* Created by zoujianglin
* 2018/8/28 0028
* advice表示拦截点,及表示用户的拦截动作
* 而spring中使用拦截器表示,因此你需要一个适配器.
*/
public interface MethodBeforeAdvice extends Advice {
void before(Method method, Object[] args, Object target) throws Throwable;
}
ThrowsAdvice 定义如下,相当于springAop中异常通知,在发生异常时将会被调用
package com.autoproxy.Adapter;
import org.aopalliance.aop.Advice;
import java.lang.reflect.Method;
/**
* Created by zoujianglin
* 2018/8/29 0029.
*/
public interface ThrowsAdvice extends Advice {
void throwAdvice(Method method, Object[] args, Object target, Throwable e) throws Throwable;
}
下篇文章我们将介绍方法拦截器等其他关键部分