springboot aop

在springboot中使用aop

1、加入pom

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

 2、定义aop切面类

/**
 * ClassName:MetricsAop <br/>
 * @author   [email protected]
 * @version  
 * @see 	 
 */
@Component
@Aspect
public class MetricsAop {
    
    //匹配com.richinfo.sipop.web.account.controller包及其子包下的所有类的所有方法  ,以及含有注解的MetricAnnotation的方法
    @Pointcut("execution(* com.richinfo.sipop.web.account.controller..*.*(..)) ")  
    public void executeService(){  
      
    }  
    
    @Before(value="executeService()")  
    public void doBeforeAdvice(JoinPoint joinPoint){  
        System.out.println("我是前置通知!!!");  
        //获取目标方法的参数信息  
        Object[] obj = joinPoint.getArgs();  
        System.out.println(JSON.toJSONString(obj));
        //AOP代理类的信息  
        System.out.println(joinPoint.getThis().getClass().getSimpleName());  
        //代理的目标对象  
        System.out.println(joinPoint.getTarget().getClass().getSimpleName());  
        //用的最多 通知的签名  
        Signature signature = joinPoint.getSignature();  
        //代理的是哪一个方法  
        System.out.println(signature.getName());  
        //AOP代理类的名字  
        System.out.println(signature.getDeclaringTypeName());  
        //AOP代理类的类(class)信息  
        System.out.println("class::::"+signature.getDeclaringType());  
        //获取RequestAttributes  
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();  
        //从获取RequestAttributes中获取HttpServletRequest的信息  
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);  
        Enumeration<String> enumeration = request.getParameterNames();  
        Map<String,String> parameterMap = Maps.newHashMap();  
        while (enumeration.hasMoreElements()){  
            String parameter = enumeration.nextElement();  
            parameterMap.put(parameter,request.getParameter(parameter));  
        }  
        String str = JSON.toJSONString(parameterMap);  
        if(obj.length > 0) {  
            System.out.println("请求的参数信息为:"+str);  
        }  
    }  
    
    /** 
     * 后置返回通知 
     * 这里需要注意的是: 
     *      如果参数中的第一个参数为JoinPoint,则第二个参数为返回值的信息 
     *      如果参数中的第一个参数不为JoinPoint,则第一个参数为returning中对应的参数 
     * returning 限定了只有目标方法返回值与通知方法相应参数类型时才能执行后置返回通知,否则不执行,对于returning对应的通知方法参数为Object类型将匹配任何目标返回值 
     * @param joinPoint 
     * @param keys 
     */  
    @AfterReturning(value="executeService()",returning = "keys")  
    public void doAfterReturningAdvice1(JoinPoint joinPoint,Object keys){  
      
        System.out.println("第一个后置返回通知的返回值:"+keys);  
    }  
      
    @AfterReturning(value="executeService()",returning = "keys",argNames = "keys")  
    public void doAfterReturningAdvice2(String keys){  
      
        System.out.println("第二个后置返回通知的返回值:"+keys);  
    }  
    
    /** 
     * 后置异常通知 
     *  定义一个名字,该名字用于匹配通知实现方法的一个参数名,当目标方法抛出异常返回后,将把目标方法抛出的异常传给通知方法; 
     *  throwing 限定了只有目标方法抛出的异常与通知方法相应参数异常类型时才能执行后置异常通知,否则不执行, 
     *      对于throwing对应的通知方法参数为Throwable类型将匹配任何异常。 
     * @param joinPoint 
     * @param exception 
     */  
    @AfterThrowing(value = "executeService()",throwing = "exception")  
    public void doAfterThrowingAdvice(JoinPoint joinPoint,Throwable exception){  
        //目标方法名:  
        System.out.println(joinPoint.getSignature().getName());  
        if(exception instanceof NullPointerException){  
            System.out.println("发生了空指针异常!!!!!");  
        }  
    }  
    
    /** 
     * 后置最终通知(目标方法只要执行完了就会执行后置通知方法) 
     * @param joinPoint 
     */  
    @After(value="executeService()")  
    public void doAfterAdvice(JoinPoint joinPoint){  
      
        System.out.println("后置通知执行了!!!!");  
    } 
    
    /** 
     * 环绕通知: 
     *   环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值。 
     *   环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型 
     */  
    @Around(value="executeService()")  
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){  
        System.out.println("环绕通知的目标方法名:"+proceedingJoinPoint.getSignature().getName());  
        try {
            Object obj = proceedingJoinPoint.proceed();  
            return obj;  
        } catch (Throwable throwable) {  
            throwable.printStackTrace();  
        }  
        return null;  
    } 
}

 3、切入有注解如MetricAnnotation的方法,并获取注解,如下

//切入controller类中使用MetricAnnotation注解的方法
    @Before("@annotation(metricAnnotation)")
    public void doBeforeAdvice(JoinPoint joinPoint, MetricAnnotation metricAnnotation){
//获取request中的参数
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);

        // 从@PathVariables中获取
        Map<String, Object> pathVariables = (Map<String, Object>) request
                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);

        String id = String.valueOf(pathVariables.get(metricAnnotation.paramField()));
        if (StringUtils.isBlank(id)) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("URI路径{},@PathVariables无参数{}的值", request.getRequestURI(), metricAnnotation.paramField());
            }
            // 从@RequestParam中获取
            id = request.getParameter(paramField);
        }

       //。。。
}

4、切入点表达式

  定义切入点需要一个包含名字和任意参数的签名,还有一个切入点表达式,就是* com.sjz.web.account.controller..*.*(..) 这一部分。 

  切入点表达式的格式:execution([可见性] 返回类型 [声明类型].方法名(参数) [异常])

  其中【】中的为可选,其他的还支持通配符的使用:

    *:匹配所有字符

      ..:一般用于匹配多个包,多个参数

      +:表示类及其子类

  运算符有:&&、||、!

切入点表达式关键词:   

    1)execution:用于匹配子表达式。

            //匹配com.sjz.model包及其子包中所有类中的所有方法,返回类型任意,方法参数任意

            @Pointcut("execution(* com.sjz.model..*.*(..))")

            public void before(){}

      2)within:用于匹配连接点所在的Java类或者包。

            //匹配Person类中的所有方法

            @Pointcut("within(com.sjz.model.Person)")

            public void before(){} 

            //匹配com.sjz包及其子包中所有类中的所有方法

            @Pointcut("within(com.sjz..*)")

            public void before(){} 

     3) this:用于向通知方法中传入代理对象的引用。

            @Before("before() && this(proxy)")

            public void beforeAdvide(JoinPoint point, Object proxy){

                  //处理逻辑

            } 

      4)target:用于向通知方法中传入目标对象的引用。

            @Before("before() && target(target)

            public void beforeAdvide(JoinPoint point, Object proxy){

                  //处理逻辑

            }

      5)args:用于将参数传入到通知方法中。

            @Before("before() && args(age,username)")

            public void beforeAdvide(JoinPoint point, int age, String username){

                  //处理逻辑

            }

      6)@within :用于匹配在类一级使用了参数确定的注解的类,其所有方法都将被匹配。 

            @Pointcut("@within(com.sjz.annotation.AdviceAnnotation)") - 所有被@AdviceAnnotation标注的类都将匹配

            public void before(){}  

      7)@target :和@within的功能类似,但必须要指定注解接口的保留策略为RUNTIME。

            @Pointcut("@target(com.sjz.annotation.AdviceAnnotation)")

            public void before(){} 

      8)@args :传入连接点的对象对应的Java类必须被@args指定的Annotation注解标注。

            @Before("@args(com.sjz.annotation.AdviceAnnotation)")

            public void beforeAdvide(JoinPoint point){

                  //处理逻辑

            }  

      9)@annotation :匹配连接点被它参数指定的Annotation注解的方法。也就是说,所有被指定注解标注的方法都将匹配。

            @Pointcut("@annotation(com.sjz.annotation.AdviceAnnotation)")

            public void before(){}

      10)bean:通过受管Bean的名字来限定连接点所在的Bean。该关键词是Spring2.5新增的。

            @Pointcut("bean(person)")

            public void before(){}

猜你喜欢

转载自gsshijun.iteye.com/blog/2408985