zoukankan      html  css  js  c++  java
  • 使用spring AOP解决调用方法时前后添加日志信息

      接着上一篇的例子,这里是使用AspectJ--当前流行的AOP框架来解决问题。

      1,首先在项目中添加AOP相关的依赖jar包;

      2,创建spring 配置文件,且在创建的时候加入aop命名空间

      3,使用spring AOP基于注解的方式

       1)在配置文件中加入如下配置:

    <!-- 使aspectJ注解起作用:自动为匹配的类生成代理对象 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

      2)把横切关注点的代码抽象到切面类中

             注意点:切面首先是一个IOC容器中的bean,即加入@component注解 ;切面需加入@Aspect注解

      3)在类中声明各种通知:声明一个方法,在方法前执行用@Before注解,在方法后执行用@After注解

      4)可以在通知方法中声明一个类型为JoinPoint的参数,就能访问连接点的细节,如方法的名称和参数等。

    具体代码如图:

    @Aspect//声明类为一个切面,需要先把类放到一个IOC容器中
    @Component
    public aspect LoggingAspect {
        //该方法是一个前置通知:在目标方法执行之前执行
        @Before(value="execution(int com.test.spring.aop.Calc.*(int, int))")
        public void beforeMethod(JoinPoint joinPoint){
            String methodName=joinPoint.getSignature().getName();
            System.out.println("the method "+methodName+" begin with "+Arrays.asList(joinPoint.getArgs()));
        }
        //该方法是一个后置通知:在目标方法执行之后执行(无论是否发生异常)
        @After(value="execution(int com.test.spring.aop.Calc.*(int, int))")
        public void afterMethod(JoinPoint joinPoint){
            String methodName=joinPoint.getSignature().getName();
            System.out.println("the method "+methodName+" end");
        }
        
    }
  • 相关阅读:
    蓝奏云的链接打不开
    数据链路层
    markdown(md)
    物理层
    计算机网络概述
    86五笔学习笔记
    Ubuntu初次使用的问题
    Hello Word!
    快速创建Flask Restful API项目
    Ubuntu环境下部署Django+uwsgi+nginx总结
  • 原文地址:https://www.cnblogs.com/sunshine2017/p/7354017.html
Copyright © 2011-2022 走看看