实现Java AOP获取方法入参

流程

步骤 描述
1 创建一个切面类,用于定义切点和通知
2 在切面类中编写@Before通知,获取方法入参
3 在Spring配置文件中配置切面和切点
4 测试切面是否成功获取方法入参

代码实现

步骤1:创建切面类

package com.example.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        System.out.println("Method arguments are : " + Arrays.toString(args));
    }
}

步骤2:配置Spring配置文件

<beans xmlns="
       xmlns:xsi="
       xsi:schemaLocation="
       

    <context:component-scan base-package="com.example.aop"/>

    <aop:aspectj-autoproxy/>
</beans>

步骤3:测试切面

package com.example;

import com.example.service.MyService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        MyService myService = (MyService) context.getBean("myService");
        myService.doSomething("Hello");
    }
}

序列图

sequenceDiagram
    participant Client
    participant Aspect
    participant Service

    Client->>Service: 调用方法
    Service->>Aspect: 执行方法
    Aspect-->>Aspect: 获取方法入参

甘特图

gantt
    title Java AOP获取方法入参实现流程
    dateFormat  YYYY-MM-DD
    section 实现流程
    创建切面类           :done, 2022-01-01, 1d
    配置Spring配置文件   :done, 2022-01-02, 1d
    测试切面             :active, 2022-01-03, 1d

通过以上步骤,你可以成功实现Java AOP获取方法入参的功能。希望你能够从中学习到相关知识,提升自己的技术能力。加油!