El uso de ProceedingJoinPoint en SpringAOP, con la forma de anotación (con ejemplos detallados)

  1. Obtener el nombre del método de punto de entrada
    getSignature()); es obtener dicha información: modificador + nombre del paquete + nombre del componente (nombre de la clase) + nombre del método,
    aquí solo necesito el nombre del método
String methodName = joinPoint.getSignature().getName()
  1. Obtener anotaciones de métodos
  • Método 1: xxxxxx es el nombre de la anotación
Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            xxxxxx annoObj= method.getAnnotation(xxxxxx.class);
        }
        return null;
  • Método 2: Ya conocemos el nombre del método y el objeto de la clase anterior, y cualquier información interna de la clase se puede obtener a través de la reflexión.
 // 切面所在类
        Object target = joinPoint.getTarget();
 
        String methodName = joinPoint.getSignature().getName();
 
        Method method = null;
        for (Method m : target.getClass().getMethods()) {
            if (m.getName().equals(methodName)) {
                method = m;
               //  xxxxxx annoObj= method.getAnnotation(xxxxxx.class);同上
                break;
            }
        }
  1. Obtenga los parámetros del método
    Aquí está la lista de parámetros del método pointcut
Object[] args = joinPoint.getArgs();

prueba

Ver para creer, puedes entender más profundamente después de probarlo una vez

@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ApiLog
{
    /**
     * 模块 
     */
    public String title() default "";

    /**
     * 日志记录service实现
     * @return
     */
    public String logService() default "operLogServiceImpl";


    /**
     * 是否保存请求的参数
     */
    public boolean isSaveRequestData() default true;

    /**
     * 是否追踪用户操作
     * @return
     */
    public boolean isTrack() default true;
}

Fideos

package com.kouryoushine.aop.test;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Aspect
@Component
public class DemoAspect {

    //切入点:aopdemo报下所有对象的save方法
    @Pointcut("execution(public * com.kouryoushine.aop.test.*.save*(..))")
    public void save(){

    }
    /**
     * 需要在update操作前后分别获取更新前后的值
     * @param
     * @return
     */

    @AfterReturning("save()")
    public void afterReturn(JoinPoint joinPoint) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        //1.获取切入点所在目标对象
        Object targetObj =joinPoint.getTarget();
        System.out.println(targetObj.getClass().getName());
        // 2.获取切入点方法的名字
        String methodName = joinPoint.getSignature().getName();
        System.out.println("切入方法名字:"+methodName);
        // 3. 获取方法上的注解
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
           ApiLog apiLog=  method.getAnnotation(ApiLog.class);
            System.out.println("切入方法注解的title:"+apiLog.title());
        }

        //4. 获取方法的参数
        Object[] args = joinPoint.getArgs();
        for(Object o :args){
            System.out.println("切入方法的参数:"+o);
        }


    }



}

clase de servicio

@Service
public class TestServcie {

    @ApiLog(title = "注解的标题",isSaveRequestData = false)
    public void save(String parm1,int parm2){
        System.out.println("执行目标对象的方法"+parm1+parm2);
    }


    public void  update(){
        System.out.println("没有注解的方法,不会被拦截");
    }
}

Métodos de prueba

  @Autowired
    TestServcie testServcie;
    @Test
    void  test6() throws Exception{

        testServcie.save("参数1字符串",33);
    }

Resultados de la prueba

com.kouryoushine.aop.test.TestServcie
切入方法名字:save
切入方法注解的title:注解的标题
切入方法的参数:参数1字符串
切入方法的参数:33

Supongo que te gusta

Origin blog.csdn.net/weixin_48453772/article/details/109486653
Recomendado
Clasificación