1、定义切入点:要拦截的方法
@Pointcut("@annotation(com.bird.aop.OperLogInject)") //所有注解@OperLogInject()的方法
public void serviceAspect() { }
//自定义注解@OperLogInject:
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLogInject {
String code() default "" ; //操作类型LogType.Desc
String content() default ""; //操作内容
}
2、定义切面:要执行的目标方法
@Aspect
public class OperLogAspect {
@After("serviceAspect()")
public void doAfter(JoinPoint joinPoint) {
//target method
}
}
3、自定义注解要用到的元注解
元注解是指注解的注解。包括 @Retention @Target @Document @Inherited四种。
3.1 @Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
3.2 @Target:定义注解的作用目标
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
由以上的源码可以知道,他的elementType 可以有多个,一个注解可以为类的,方法的,字段的等等
3.3 @Document:说明该注解将被包含在javadoc中
3.4 @Inherited:说明子类可以继承父类中的该注解