如何使用Spring AOP预处理Controller的参数
作者:rw-just-go-forward 发布时间:2022-09-11 10:01:56
Spring AOP预处理Controller的参数
实际编程中,可能会有这样一种情况,前台传过来的参数,我们需要一定的处理才能使用
比如有这样一个Controller
@Controller
public class MatchOddsController {
@Autowired
private MatchOddsServcie matchOddsService;
@RequestMapping(value = "/listOdds", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<OddsModel> listOdds(@RequestParam Date startDate, @RequestParam Date endDate) {
return matchOddsService.listOdds(startDate, endDate);
}
}
前台传过来的startDate和endDate是两个日期,实际使用中我们需要将之转换为两个日期对应的当天11点,如果只有这么一个类的话,我们是可以直接在方法最前面处理就可以了
但是,还有下面两个类具有同样的业务逻辑
@Controller
public class MatchProductController {
@Autowired
private MatchProductService matchProductService;
@RequestMapping(value = "/listProduct", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public List<ProductModel> listProduct(@RequestParam Date startDate, @RequestParam Date endDate) {
return matchProductService.listMatchProduct(startDate, endDate);
}
}
@Controller
public class MatchController {
@Autowired
private MatchService matchService;
@RequestMapping(value = "/listMatch", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<MatchModel> listMatch(@RequestParam Date startDate, @RequestParam Date endDate) {
return matchService.listMatch(startDate, endDate);
}
}
当然也可以写两个util方法,分别处理startDate和endDate,但是为了让Controller看起来更干净一些,我们还是用AOP来实现吧,顺便为AOP更复杂的应用做做铺垫
本应用中使用Configuration Class来进行配置,
主配置类如下:
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = true) //开启AspectJ代理,并将proxyTargetClass置为true,表示启用cglib对Class也进行代理
public class Application extends SpringBootServletInitializer {
...
}
下面新建一个Aspect类,代码如下
@Aspect //1
@Configuration //2
public class SearchDateAspect {
@Pointcut("execution(* com.ronnie.controller.*.list*(java.util.Date,java.util.Date)) && args(startDate,endDate)") //3
private void searchDatePointcut(Date startDate, Date endDate) { //4
}
@Around(value = "searchDatePointcut(startDate,endDate)", argNames = "startDate,endDate") //5
public Object dealSearchDate(ProceedingJoinPoint joinpoint, Date startDate, Date endDate) throws Throwable { //6
Object[] args = joinpoint.getArgs(); //7
if (args[0] == null) {
args[0] = Calendars.getTodayEleven();
args[1] = DateUtils.add(new Date(), 7, TimeUnit.DAYS);//默认显示今天及以后的所有 *
} else {
args[0] = DateUtils.addHours(startDate, 11);
args[1] = DateUtils.addHours(endDate, 11);
}
return joinpoint.proceed(args); //8
}
}
分别解释一下上面各个地方的意思,标号与语句之后的注释一致
表示这是一个切面类
表示这个类是一个配置类,在ApplicationContext启动时会加载配置,将这个类扫描到
定义一个切点,execution(* com.ronnie.controller.*.list*(java.util.Date,java.util.Date))表示任意返回值,在com.ronnie.controller包下任意类的以list开头的方法,方法带有两个Date类型的参数,args(startDate,endDate)表示需要Spring传入这两个参数
定义切点的名称
配置环绕通知
ProceedingJoinPoint会自动传入,用于处理真实的调用
获取参数,下面代码是修改参数
使用修改过的参数调用目标类
更多可参考
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
AOP获取参数名称
由于项目中打印日志的需要,研究了一下在aop中,获取参数名称的方法。
1、jdk1,8中比较简单,直接通过joinPoint中的getSignature()方法即可获取
Signature signature = joinpoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
String[] strings = methodSignature.getParameterNames();
System.out.println(Arrays.toString(strings));
2.通用方法。比较麻烦
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
String classType = joinPoint.getTarget().getClass().getName();
Class<?> clazz = Class.forName(classType);
String clazzName = clazz.getName();
String methodName = joinPoint.getSignature().getName(); //获取方法名称
Object[] args = joinPoint.getArgs();//参数
//获取参数名称和值
Map<String,Object > nameAndArgs = getFieldsName(this.getClass(), clazzName, methodName,args);
System.out.println(nameAndArgs.toString());
//为了省事,其他代码就不写了,
return result = joinPoint.proceed();
}
private Map<String,Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
Map<String,Object > map=new HashMap<String,Object>();
ClassPool pool = ClassPool.getDefault();
//ClassClassPath classPath = new ClassClassPath(this.getClass());
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
// exception
}
// String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++){
map.put( attr.variableName(i + pos),args[i]);//paramNames即参数名
}
//Map<>
return map;
}
来源:https://blog.csdn.net/RO_wsy/article/details/50858810


猜你喜欢
- 简介JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Validation。在任何时候,当你要处理一个应用程序的业务逻
- C#实现的鼠标钩子,可以获取鼠标在屏幕中的坐标,记得要以管理员权限运行才行using System;using System.Collect
- AIDL是Android接口定义语言,它可以用于让某个Service与多个应用程序组件之间进行跨进程通信,从而可以实现多个应用程序共享同一个
- java通过IP解析地理位置在项目开发中,需要在登录日志或者操作日志中记录客户端ip所在的地理位置。目前根据ip定位地理位置的第三方api有
- 开发中对版本进行检查并更新的需求基本是所有应用必须有的功能,可是在实际开发中有些朋友就容易忽略一些细节。版本更新的基本流程:一般是将本地版本
- hashCode()和equals()方法可以说是Java完全面向对象的一大特色.它为我们的编程提供便利的同时也带来了很多危险.这篇文章我们
- 如何解决yml没有spring小叶子标志我的idea springboot项目中有两个.yml文件,一个application.yml,一个
- 1.什么是thread当我们提及多线程的时候会想到thread和threadpool,这都是异步操作,threadpool其实就是threa
- 本文实例为大家分享了android使用OPENGL ES绘制圆柱体的具体代码,供大家参考,具体内容如下效果图:编写jiem.java&nbs
- 参考ColorComboBox做修改,并对颜色名做些修正,用于CR MVMixer产品中,聊作备忘~效果图:代码://颜色拾取框using
- 上下文:程序运行需要的环境(外部变量)上下文切换:将之前的程序需要的外部变量复制保存,然后切换到新的程序运行环境系统调用:(用户态陷入操作系
- 为什么需要方法回调?方法回调是功能定义和功能分离的一种手段,是一种松耦合的设计思想。在JAVA中回调是通过接口来实现的。作为一种系统架构,必
- 首先定义两个示例类ClassA,ClassB,用于后续的示例演示package cn.lzrabbit;public class Class
- android开发中为activity增加左右手势识别,如右滑关闭当前页面。/* * for左右手势 *&n
- 用了MyBatis的同行,应该见过foreach,它一般是这样用的:<select id="foreachTest"
- 在JDK的Collection中我们时常会看到类似于这样的话:例如,ArrayList:注意,迭代器的快速失败行为无法得到保证,因为一般来说
- 本文实例讲述了Java使用synchronized实现互斥锁功能。分享给大家供大家参考,具体如下:代码package per.thread;
- 可能导致问题的原因:1.nacos中的配置文件名不规范,官网有命名规则:“前缀”-&ldqu
- 首先我们发现现在我们所用的android智能手机大部分都有当你在打电话时按power键来挂断电话,一般都是在设置中。 我主要是在原生源码中添
- 本文实例为大家分享了android自定义波浪加载动画的具体代码,供大家参考,具体内容如下效果图1.自定义控件 WaveViewpackage