zoukankan      html  css  js  c++  java
  • 一个最简单的通过自定义注解形式实现AOP的例子

    1.首先实现AOP实例的第一步即声明切面类,两种方式(1.基于注解形式@Aspect,2.基于xml配置,一般都通过注解来声明切面类)

    2.切入点表达式大致也有两种,一种是直接根据方法的签名来匹配各种方法@Pointcut("execution(xxxxxx表达式)"),另一种即标题的通过自定义注解的形式@Pointcut("@annotation(注解名)")

    3.首先自定义注解

     @Target({ElementType.METHOD})
        @Retention(RetentionPolicy.RUNTIME)
        @Documented
        public @interface ExtendPoint {
        }


    这里顺便记录java中四大元注解的作用:
       @Target 表示该注解用于什么地方,可能的值在枚举类 ElemenetType 中,包括:

              ElemenetType.CONSTRUCTOR----------------------------构造器声明

              ElemenetType.FIELD --------------------------------------域声明(包括 enum 实例)

              ElemenetType.LOCAL_VARIABLE------------------------- 局部变量声明

              ElemenetType.METHOD ----------------------------------方法声明

              ElemenetType.PACKAGE --------------------------------- 包声明

              ElemenetType.PARAMETER ------------------------------参数声明

              ElemenetType.TYPE--------------------------------------- 类,接口(包括注解类型)或enum声明

               

         @Retention 表示在什么级别保存该注解信息。可选的参数值在枚举类型 RetentionPolicy 中,包括

              RetentionPolicy.SOURCE ---------------------------------注解将被编译器丢弃

              RetentionPolicy.CLASS -----------------------------------注解在class文件中可用,但会被VM丢弃

              RetentionPolicy.RUNTIME VM-------将在运行期也保留注释,因此可以通过反射机制读取注解的信息。

               

          @Documented 将此注解包含在 javadoc 中 ,它代表着此注解会被javadoc工具提取成文档。在doc文档中的内容会因为此注解的信息内容不同而不同。相当与@see,@param 等。

           

          @Inherited 允许子类继承父类中的注解。

    4.声明切面类

    @Aspect
    @Component
    public class ExtendAspect {
     
        @Pointcut("@annotation(ExtendPoint)")
        private void aspectjMethod(){};
     
        @Before("aspectjMethod()")
        public void before(JoinPoint jp, ExtendPoint ep){
        }
     
        @Around(value = "aspectjMethod()")
        public Object around(ProceedingJoinPoint point) throws Throwable {
            Object[] args = point.getArgs();
            //用改变后的参数执行目标方法
            Object returnValue = point.proceed(args);
            return returnValue;
        }
     
        @AfterReturning(value = "aspectjMethod()", returning = "returnValue")
        public void log(JoinPoint point, Object returnValue){
     
        }
     
        @After(value = "aspectjMethod()")
        public void after(JoinPoint point){
        }
     
        @AfterThrowing(value = "aspectjMethod()", throwing = "ex")
        public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) {
        }
    }
  • 相关阅读:
    [leetcode]Palindrome Partitioning II
    [wikioi]传纸条
    [leetcode]Palindrome Partitioning
    [leetcode]Convert Sorted List to Binary Search Tree
    [topcoder]ActivateGame
    [topcoder]NinePuzzle
    [topcoder]BestRoads
    [topcoder]IncreasingSubsequences
    [leetcode]Surrounded Regions
    CF 432B :Football Kit
  • 原文地址:https://www.cnblogs.com/leeego-123/p/11390285.html
Copyright © 2011-2022 走看看