Spring-Aop实现的三种方式

发布时间 2023-09-03 18:49:33作者: DengSr
  • 学习Spring中的Aop思想:将公共业务(日志、安全等)和领域业务结合起来,当执行领域业务时会把公共业务加进来,实现公共业务的重复利用。其本质还是动态代理(代理某一类业务)。
  • 实现Aop的三种方式
  1. 通过spring的ApI实现:需要用到两个方法,前置增强需要实现MethodBeforeAdvice接口的方法 。后置增强需要实现AfterReturningAdvice 接口的方法,具体实现代码情况如下:
    //前置增强
    public class Log implements MethodBeforeAdvice {
    
       //method : 要执行的目标对象的方法
       //objects : 被调用的方法的参数
       //Object : 目标对象
       @Override
       public void before(Method method, Object[] objects, Object o) throws Throwable {
           System.out.println( o.getClass().getName() + "的" + method.getName() + "方法被执行了");
      }
    }
    
    
    //后置增强
    public class AfterLog implements AfterReturningAdvice {
       //returnValue 返回值
       //method被调用的方法
       //args 被调用的方法的对象的参数
       //target 被调用的目标对象
       @Override
       public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
           System.out.println("执行了" + target.getClass().getName()
           +"的"+method.getName()+"方法,"
           +"返回值:"+returnValue);
      }
    }

     

  2. 自定义类来实现ApI:需要使用Aop标签来进行配置,具体配置情况如下:
    <bean id="diy" class="com.deng.pojo.DiyPointCut"/>       //DiyPointCut是自定义的类
        <aop:config>
            <aop:aspect ref="diy">
                <aop:pointcut id="diyPointCut" expression="execution(* com.deng.service.UserServiceImpl.*(..))"/>
                <aop:after method="after" pointcut-ref="diyPointCut"/>        //在方法执行前打印
                <aop:before method="before" pointcut-ref="diyPointCut"/>      //方法执行后打印
            </aop:aspect>
    
        </aop:config>

     

  3. 通过注解实现Aop:其中需要在bean中开启注解支持
    <aop:aspectj-autoproxy/>

    具体注解代码实现情况如下

     1 package com.deng.annotation;
     2 
     3 import org.aspectj.lang.ProceedingJoinPoint;
     4 import org.aspectj.lang.annotation.After;
     5 import org.aspectj.lang.annotation.Around;
     6 import org.aspectj.lang.annotation.Aspect;
     7 import org.aspectj.lang.annotation.Before;
     8 
     9 @Aspect   //标注这个类是一个切面
    10 public class AnnotationPointCut {
    11 
    12     @Before("execution(* com.deng.service.UserServiceImpl.*(..))")        //在执行UserServiceImpl这个类的方法之前才实现
    13     public void Before()
    14     {
    15         System.out.println("方法执行前");
    16     }
    17 
    18     @After("execution(* com.deng.service.UserServiceImpl.*(..))")         //在执行UserServiceImpl这个类的方法之后才实现
    19     public void After(){
    20         System.out.println("方法执行后");
    21     }
    22 
    23     @Around(("execution(* com.deng.service.UserServiceImpl.*(..))"))      //在执行UserServiceImpl这个过程中实现
    24     public void around(ProceedingJoinPoint jp) throws Throwable {
    25         System.out.println("环绕前");
    26         Object proceed = jp.proceed();
    27 
    28         System.out.println("环绕后");
    29     }
    30 }