如何通过Spring Security的MethodInvocation获取精准的方法参数信息
解决方案
核心说明
MethodInvocation是AOP联盟定义的通用拦截接口,不属于Spring Security专属组件,相关行为遵循Spring AOP的统一规范,因此相关规则不会在Spring Security文档中单独说明。
1. 获取方法参数列表(含名称与类型)
首先通过MethodInvocation#getMethod()拿到被拦截方法的java.lang.reflect.Method实例,再通过该实例获取参数元信息:
- 参数类型:调用
Method#getParameterTypes()返回Class<?>[]数组,元素顺序和方法声明的参数顺序完全一致 - 参数名称:使用Spring自带的
DefaultParameterNameDiscoverer工具类获取,Java 8+环境下如果编译时开启了-parameters参数,可稳定拿到原生命名,否则会从调试信息中尝试解析。
2. 获取参数实际取值
直接调用MethodInvocation#getArguments()返回Object[]数组,该数组的元素顺序和方法声明的参数顺序完全一一对应:
- 数组元素的运行时类型和方法入参的实际传入值完全匹配,若方法声明为基本类型,返回值会自动装箱为对应的包装类型(比如
int参数会装箱为Integer对象) - 若调用时某参数传入
null,对应位置的元素即为null
完整示例代码
import org.aopalliance.intercept.MethodInvocation; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; import java.lang.reflect.Method; public class MethodParamResolver { private static final ParameterNameDiscoverer NAME_DISCOVERER = new DefaultParameterNameDiscoverer(); public void resolve(MethodInvocation invocation) { // 获取被拦截的目标方法 Method targetMethod = invocation.getMethod(); // 获取参数类型数组 Class<?>[] paramTypes = targetMethod.getParameterTypes(); // 获取参数名称数组 String[] paramNames = NAME_DISCOVERER.getParameterNames(targetMethod); // 获取实际参数值数组 Object[] actualArgs = invocation.getArguments(); // 遍历输出所有参数信息 for (int i = 0; i < paramTypes.length; i++) { String paramName = paramNames != null ? paramNames[i] : "无法解析(建议开启编译参数-parameters)"; System.out.printf("第%d个参数:类型=%s,名称=%s,实际值=%s%n", i + 1, paramTypes[i].getName(), paramName, actualArgs[i]); } } }
注意事项
- 若参数名称解析失败,优先检查编译配置是否开启了
-parameters参数,IDEA和Maven/Gradle都有对应的配置项 - 处理
getArguments()返回值时要做好非空判断,避免空指针异常 - 若被拦截方法是接口方法,
getMethod()默认返回的是接口的方法实例,要拿到实现类的方法可以通过invocation.getThis().getClass()的对应方法进一步处理
内容的提问来源于stack exchange,提问作者hotmeatballsoup
相关产品推荐
相关产品推荐

