java自定义注解

1、定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Validate {
    String url() default "";

    enum type{GET, POST, DELETE};

    String[] method() default {};
}

2、使用注解

@RestController
@RequestMapping(value = "/index")
public class IndexController {
    
    @GetMapping()
    @Validate
    public String index() {
        return "index";
    }
}

3、提供切面对注解数据进行操作

/**
 * 描述:@annotation:标注了某个注解的所有方法
 * execution(* com.software.*.*(..))
 * 第一个*代表任意的的修饰符和返回值,第二个*代表任意的类,第三个*代表类的任意方法,最后一个..匹配任意数量的参数
 *
 * 1、@Before:前置通知,在方法执行之前执行的通知
 * 2、@After:后置通知,在方法执行之后执行,即方法返回结果或者抛出异常的时候
 * 3、@AfterRunning:返回通知,在方法返回结果之后执行(ps:无论方法是正常返回,还是抛出异常,后置通知都会执行,如果
 * 只想在方法返回的时候执行,应使用返回通知代替后置通知)
 * 4、@AfterThrowing:异常通知,在方法抛出异常之后执行
 * 5、@Around:环绕通知,围绕着方法执行(即方法前后都有执行)
 *
 * @ClassName ValidateAspect
 * @Author 徐旭
 * @Date 2018/11/5 15:06
 * @Version 1.0
 */
@Aspect
@Component
public class ValidateAspect {

    /**
     * 切入点,表示拦截的切入点方法,注解在方法级别之上,但是不执行方法体,只表示切入点的入口
     */
    @Pointcut(value = "@annotation(com.example.annotation.annotation.Validate)")
    public void pointcut() {
    }

    /**
     * 方法执行前后
     * @param point
     * @param validate
     * @return
     */
    @Around(value = "pointcut() && @annotation(validate)")
    public Object around(ProceedingJoinPoint point, Validate validate) {
        String url = validate.url();
        
        Class clazz = point.getTarget().getClass();
        Method method = ((MethodSignature)point.getSignature()).getMethod();
        check(method, Validate.class);
        
        System.out.println("执行了类:" + clazz + "方法:" + method + " 请求地址:" + url);

        try {
            System.out.println(point.proceed());
            return point.proceed();
        } catch (Throwable throwable) {
            return throwable.getMessage();
        }
    }

    /**
     * 方法执行后,@AfterReturning的value指定所有带有@Validate注解的方法体为切点
     * @param point
     * @param validate
     * @param result
     * @return
     */
    @AfterReturning(value = "pointcut() && @annotation(validate)", returning = "result") 
    public Object afterReturning(JoinPoint point, Validate validate, Object result) {
        return result;
    }

    /**
     * 出现异常时执行
     * @param point
     * @param validate
     */
    @AfterThrowing(value = "pointcut() && @annotation(validate)")
    public void afterThrowing(JoinPoint point, Validate validate) {
        System.out.println("出现异常");
    }

    public static  boolean check(Method method, Class annotation) {
            List list = Arrays.asList(method.getAnnotations());
    
            for (int i = 0; i < list.size(); i++) {
                Annotation ann = list.get(i);
                // 找到自己的注解
                if (ann.annotationType().equals(annotation)) {
                    System.out.println("test");
                }
            }
            return true;
        }
}

你可能感兴趣的:(java自定义注解)