如何使用Spring AOP预处理Controller的参数
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; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。
相关文章
- 这篇文章主要介绍了Spring AOP 对象内部方法间的嵌套调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-29
Spring Cloud 中@FeignClient注解中的contextId属性详解
这篇文章主要介绍了Spring Cloud 中@FeignClient注解中的contextId属性详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-25Springboot如何实现Web系统License授权认证
这篇文章主要介绍了Springboot如何实现Web系统License授权认证,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-05-28- 这篇文章主要给大家介绍了关于Nest.js参数校验和自定义返回数据格式的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-28
如何在Spring WebFlux的任何地方获取Request对象
这篇文章主要介绍了如何在Spring WebFlux的任何地方获取Request对象,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下...2021-01-26- 这篇文章主要介绍了详解SpringCloudGateway内存泄漏问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-07-16
- 这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
PHP中empty和isset对于参数结构的判断及empty()和isset()的区别
废话不多说了,直接给大家贴代码了。<?php class test{} $a1 = null; $a2 = ""; //$a3 = $a4 = 0; $a5 = '0'; $a6 = false; $a7 = array(); //var $a8; $a9 = new test(); for ($i=1; $i <=9 ; $i++) {...2015-11-24- 这篇文章主要介绍了java正则表达式判断前端参数修改表中另一个字段的值,需要的朋友可以参考下...2021-05-07
- mysql安装成功后有几个默认的配置模板,列表如下: my-huge.cnf : 用于高端产品服务器,包括1到2GB RAM,主要运行mysql my-innodb-heavy-4G.ini : 用于只有innodb的安装,最多有4GB RAM,支持大的查询和低流量 my-large.cnf : 用于...2015-03-15
Spring Boot项目@RestController使用重定向redirect方式
这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02- 这篇文章主要介绍了C#泛型的类型参数约束的相关资料,文中讲解非常细致,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下...2020-07-31
- @Autowired 注解的主要功能就是完成自动注入,使用也非常简单,但这篇文章主要给大家介绍了关于Spring为什么不推荐使用@Autowired注解的相关资料,需要的朋友可以参考下...2021-11-03
- 这篇文章主要给大家介绍了关于C#中out参数、ref参数与值参数的用法及区别的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
Springboot如何使用mybatis实现拦截SQL分页
这篇文章主要介绍了Springboot使用mybatis实现拦截SQL分页,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-19- 这篇文章主要介绍了Java线程池中的各个参数如何合理设置操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-06-19
- 这篇文章主要介绍了vue+axios全局添加请求头和参数操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-24
处理@PathVariable注解允许参数为空、允许不传参数的问题
这篇文章主要介绍了处理@PathVariable注解允许参数为空、允许不传参数的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-23- 这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
- 这篇文章主要介绍了SpringMVC文件上传原理及实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-07-15