问题
使用 AOP 技术怎么获取传递到Controller层的参数
回答
在 AOP 切面中,我们可以通过 ProceedingJoinPoint 对象获取到被拦截的方法的参数列表。对于传递到 Controller 层的参数,可以通过 HttpServletRequest 或者 @RequestParam 注解来获取。
例如,假设我们有一个 Controller 类,其中包含一个方法 example:
@RestController
@RequestMapping("/example")
public class ExampleController {
@GetMapping("/{id}")
public String example(@PathVariable("id") Integer id, @RequestParam("name") String name) {
return "id: " + id + ", name: " + name;
}
}
我们想要在 AOP 切面中获取到 id 和 name 参数,可以通过如下代码实现:
@Aspect
@Component
public class MyAspect {
@Around("execution(* com.example.controller.ExampleController.example(..)) && args(id, name,..)")
public Object example(ProceedingJoinPoint pjp, Integer id, String name) throws Throwable {
// 访问传递到 Controller 层的参数
System.out.println("id: " + id);
System.out.println("name: " + name);
// 调用原有方法
return pjp.proceed();
}
}
上述代码中,我们使用了 args 来指定传递到 example 方法中的参数,并将这些参数作为切面方法的参数列表。在切面方法中,我们可以直接访问 id 和 name 参数。需要注意的是,切面方法需要在被拦截的方法执行之前或之后执行,因此需要调用 pjp.proceed() 来执行被拦截的方法。