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");
        }
        
    }
  • 相关阅读:
    C#和Modbus通信工程
    C#中JS和Flash中AS 3.0通信交互
    创建型-建造者模式(Builder)
    结构型-享元模式(Flyweight)
    行为型-模板方法模式(Template Method)
    创建型-原型模式(Prototype)
    行为型-状态模式(State)
    结构型-桥接模式(Bridge)
    行为型-中介者模式(Mediator)
    行为型-备忘录模式(Memento)
  • 原文地址:https://www.cnblogs.com/sunshine2017/p/7354017.html
Copyright © 2011-2022 走看看