返回

SpringBoot增强使用-利用变量获取method并调用

后端

前言

我们使用 SpringBoot 开发应用程序时,经常会遇到需要增强原有功能的情况,例如添加日志、权限控制、性能指标等。传统上,我们会使用 AOP (Aspect Oriented Programming) 来实现这些功能,但 AOP 有时会带来一些性能开销和代码复杂性。

使用 SpringBoot 增强使用的方法

SpringBoot 中,我们可以使用一种更简单的方式来增强原有功能,那就是使用 MethodParameterInvocation 接口。这些接口提供了很多方便的方法,可以轻松地获取当前执行的方法信息,并执行一些操作。

具体操作步骤

  1. 获取 MethodParameterInvocation 接口

要获取 MethodParameterInvocation 接口,我们需要在控制类中添加一个方法参数,类型分别为 MethodParameterInvocation,如下:

public void enhanceMethod(MethodParameter methodParameter, InvocationInvocation) {
  // do something
}
  1. 获取当前执行的方法信息

获取当前执行的方法信息,我们可以使用 MethodParametergetAnnotatedTypegetAnnotatedGenericParametergetExecutable 方法,如下:

AnnotatedType annotatedType = methodParameter.getAnnotatedType();
AnnotatedGenericParameter annotatedGenericParameter = methodParameter.getAnnotatedGenericParameter();
Executable method = methodParameter.getExecutable();
  1. 调用指定的方法

获取到当前执行的方法信息后,我们可以使用 Invocation 接口的 invoke 方法调用指定的方法,如下:

Object result = invoker.invoke(args);

总结

使用 MethodParameterInvocation 接口来增强原有功能是一种简单而有效的方法,它可以避免 AOP 的一些性能开销和代码复杂性。同时,这种方式更加的方便和快捷,而且可以很好地进行解耦,让代码更加的整洁和可读性,适合多种场景,值得一试。