SpringAOP 如何通过JoinPoint获取参数名和值

 更新时间:2021年06月17日 09:04:34   作者:alwaysBrother  
这篇文章主要介绍了SpringAOP 通过JoinPoint获取参数名和值的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringAOP 通过JoinPoint获取参数名和值

在Java8之前,代码编译为class文件后,方法参数的类型固定,但是方法名称会丢失,方法名称会变成arg0、arg1….。在Java8开始可以在class文件中保留参数名。

public void tet(JoinPoint joinPoint) {
        // 下面两个数组中,参数值和参数名的个数和位置是一一对应的。
        Object[] args = joinPoint.getArgs(); // 参数值
        String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames(); // 参数名
}

注意:

IDEA 只有设置了 Java 编译参数才能获取到参数信息。并且jdk要在1.8及以上版本。

这里写图片描述

Maven中开启的办法

增加compilerArgs 参数

 <plugins>
     <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>${maven_compiler_plugin_version}</version>
         <configuration>
             <source>${java_source_version}</source>
             <target>${java_target_version}</target>
             <encoding>${file_encoding}</encoding>
             <compilerArgs>
                 <arg>-parameters</arg>
             </compilerArgs>
         </configuration>
     </plugin>
</plugins>

Eclipse中开启的办法

Preferences->java->Compiler下勾选Store information about method parameters选项。

这样在使用eclipse编译java文件的时候就会将参数名称编译到class文件中。

SpringAOP中JoinPoint对象的使用方法

JoinPoint 对象

JoinPoint对象封装了SpringAop中切面方法的信息,在切面方法中添加JoinPoint参数,就可以获取到封装了该方法信息的JoinPoint对象.

常用API

方法名 功能
Signature getSignature(); 获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息
Object[] getArgs(); 获取传入目标方法的参数对象
Object getTarget(); 获取被代理的对象
Object getThis(); 获取代理对象

ProceedingJoinPoint对象

ProceedingJoinPoint对象是JoinPoint的子接口,该对象只用在@Around的切面方法中,

添加了以下两个方法。

Object proceed() throws Throwable //执行目标方法 
Object proceed(Object[] var1) throws Throwable //传入的新的参数去执行目标方法 

Demo

切面类

@Aspect
@Component
public class aopAspect {
    /**
     * 定义一个切入点表达式,用来确定哪些类需要代理
     * execution(* aopdemo.*.*(..))代表aopdemo包下所有类的所有方法都会被代理
     */
    @Pointcut("execution(* aopdemo.*.*(..))")
    public void declareJoinPointerExpression() {}
    /**
     * 前置方法,在目标方法执行前执行
     * @param joinPoint 封装了代理方法信息的对象,若用不到则可以忽略不写
     */
    @Before("declareJoinPointerExpression()")
    public void beforeMethod(JoinPoint joinPoint){
        System.out.println("目标方法名为:" + joinPoint.getSignature().getName());
        System.out.println("目标方法所属类的简单类名:" +        joinPoint.getSignature().getDeclaringType().getSimpleName());
        System.out.println("目标方法所属类的类名:" + joinPoint.getSignature().getDeclaringTypeName());
        System.out.println("目标方法声明类型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
        //获取传入目标方法的参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            System.out.println("第" + (i+1) + "个参数为:" + args[i]);
        }
        System.out.println("被代理的对象:" + joinPoint.getTarget());
        System.out.println("代理对象自己:" + joinPoint.getThis());
    }
    /**
     * 环绕方法,可自定义目标方法执行的时机
     * @param pjd JoinPoint的子接口,添加了
     *            Object proceed() throws Throwable 执行目标方法
     *            Object proceed(Object[] var1) throws Throwable 传入的新的参数去执行目标方法
     *            两个方法
     * @return 此方法需要返回值,返回值视为目标方法的返回值
     */
    @Around("declareJoinPointerExpression()")
    public Object aroundMethod(ProceedingJoinPoint pjd){
        Object result = null;
        try {
            //前置通知
            System.out.println("目标方法执行前...");
            //执行目标方法
            //result = pjd.proeed();
            //用新的参数值执行目标方法
            result = pjd.proceed(new Object[]{"newSpring","newAop"});
            //返回通知
            System.out.println("目标方法返回结果后...");
        } catch (Throwable e) {
            //异常通知
            System.out.println("执行目标方法异常后...");
            throw new RuntimeException(e);
        }
        //后置通知
        System.out.println("目标方法执行后...");
        return result;
    }
}

被代理类

/**
 * 被代理对象
 */
@Component
public class TargetClass {
    /**
     * 拼接两个字符串
     */
    public String joint(String str1, String str2) {
        return str1 + "+" + str2;
    }
}

测试类

public class TestAop {
    @Test
    public void testAOP() {
        //1、创建Spring的IOC的容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:bean.xml");
        //2、从IOC容器中获取bean的实例
        TargetClass targetClass = (TargetClass) ctx.getBean("targetClass");
        //3、使用bean
        String result = targetClass.joint("spring","aop");
        System.out.println("result:" + result);
    }
}

输出结果

目标方法执行前...
目标方法名为:joint
目标方法所属类的简单类名:TargetClass
目标方法所属类的类名:aopdemo.TargetClass
目标方法声明类型:public
第1个参数为:newSpring
第2个参数为:newAop
被代理的对象:aopdemo.TargetClass@4efc180e
代理对象自己:aopdemo.TargetClass@4efc180e (和上面一样是因为toString方法也被代理了)
目标方法返回结果后...
目标方法执行后...
result:newSpring+newAop

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Springboot中使用Filter实现Header认证详解

    Springboot中使用Filter实现Header认证详解

    这篇文章主要介绍了Springboot中使用Filter实现Header认证详解,当在 web.xml 注册了一个 Filter 来对某个 Servlet 程序进行拦截处理时,它可以决定是否将请求继续传递给 Servlet 程序,以及对请求和响应消息是否进行修改,需要的朋友可以参考下
    2023-08-08
  • SpringBoot获取配置文件内容的几种方式总结

    SpringBoot获取配置文件内容的几种方式总结

    大家都知道SpringBoot获取配置文件的方法有很多,下面这篇文章主要给大家介绍了关于SpringBoot获取配置文件内容的几种方式,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-02-02
  • Java字符串格式化,{}占位符根据名字替换实例

    Java字符串格式化,{}占位符根据名字替换实例

    这篇文章主要介绍了Java字符串格式化,{}占位符根据名字替换实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-10-10
  • SpringBoot加载启动的源码解析

    SpringBoot加载启动的源码解析

    这篇文章主要介绍了SpringBoot加载启动的源码解析,@SpringBootApplication注解是Spring Boot的核心注解,它其实是一个组合注解,本身其实也是一个IoC容器的配置类,需要的朋友可以参考下
    2023-12-12
  • JDK从8升级到21的问题集(附案例代码)

    JDK从8升级到21的问题集(附案例代码)

    JDK 8升级到JDK 21是一个重要的版本迁移,涉及语法、模块化、API变更等多方面调整,这篇文章主要介绍了JDK从8升级到21问题的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-09-09
  • SpringBoot整合ElasticSearch实践

    SpringBoot整合ElasticSearch实践

    本篇文章主要介绍了SpringBoot整合ElasticSearch实践,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-05-05
  • Java中对象 和 json 互转四种方式 json-lib、Gson、FastJson、Jackson

    Java中对象 和 json 互转四种方式 json-lib、Gson、FastJson、Jackson

    这篇文章主要介绍了Java中对象 和 json 互转 四种方式 json-lib、Gson、FastJson、Jackson,需要的朋友可以参考下
    2023-11-11
  • RateLimit-使用guava来做接口限流代码示例

    RateLimit-使用guava来做接口限流代码示例

    这篇文章主要介绍了RateLimit-使用guava来做接口限流代码示例,具有一定借鉴价值,需要的朋友可以参考下
    2018-01-01
  • springboot整合gateway的详细过程

    springboot整合gateway的详细过程

    本文介绍了如何配置和使用Spring Cloud Gateway构建一个API网关,通过实例代码介绍了springboot整合gateway的过程,需要的朋友可以参考下
    2025-01-01
  • Java使用POI实现导出Excel的方法详解

    Java使用POI实现导出Excel的方法详解

    在项目开发中往往需要使用到Excel的导入和导出,导入就是从Excel中导入到DB中,而导出就是从DB中查询数据然后使用POI写到Excel上。本文将利用POI实现导出Excel,需要的可以参考一下
    2022-10-10

最新评论