经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
如何使用Spring AOP预处理Controller的参数
来源:jb51  时间:2021/8/9 13:56:47  对本文有异议

Spring AOP预处理Controller的参数

实际编程中,可能会有这样一种情况,前台传过来的参数,我们需要一定的处理才能使用

比如有这样一个Controller

  1. @Controller
  2. public class MatchOddsController {
  3. @Autowired
  4. private MatchOddsServcie matchOddsService;
  5. @RequestMapping(value = "/listOdds", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
  6. @ResponseBody
  7. public List<OddsModel> listOdds(@RequestParam Date startDate, @RequestParam Date endDate) {
  8. return matchOddsService.listOdds(startDate, endDate);
  9. }
  10. }

前台传过来的startDate和endDate是两个日期,实际使用中我们需要将之转换为两个日期对应的当天11点,如果只有这么一个类的话,我们是可以直接在方法最前面处理就可以了

但是,还有下面两个类具有同样的业务逻辑

  1. @Controller
  2. public class MatchProductController {
  3. @Autowired
  4. private MatchProductService matchProductService;
  5. @RequestMapping(value = "/listProduct", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
  6. @ResponseBody
  7. public List<ProductModel> listProduct(@RequestParam Date startDate, @RequestParam Date endDate) {
  8. return matchProductService.listMatchProduct(startDate, endDate);
  9. }
  10. }
  1. @Controller
  2. public class MatchController {
  3. @Autowired
  4. private MatchService matchService;
  5. @RequestMapping(value = "/listMatch", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
  6. @ResponseBody
  7. public List<MatchModel> listMatch(@RequestParam Date startDate, @RequestParam Date endDate) {
  8. return matchService.listMatch(startDate, endDate);
  9. }
  10. }

当然也可以写两个util方法,分别处理startDate和endDate,但是为了让Controller看起来更干净一些,我们还是用AOP来实现吧,顺便为AOP更复杂的应用做做铺垫

本应用中使用Configuration Class来进行配置,

主配置类如下:

  1. @SpringBootApplication
  2. @EnableAspectJAutoProxy(proxyTargetClass = true) //开启AspectJ代理,并将proxyTargetClass置为true,表示启用cglib对Class也进行代理
  3. public class Application extends SpringBootServletInitializer {
  4. ...
  5. }

下面新建一个Aspect类,代码如下

  1. @Aspect //1
  2. @Configuration //2
  3. public class SearchDateAspect {
  4. @Pointcut("execution(* com.ronnie.controller.*.list*(java.util.Date,java.util.Date)) && args(startDate,endDate)") //3
  5. private void searchDatePointcut(Date startDate, Date endDate) { //4
  6. }
  7. @Around(value = "searchDatePointcut(startDate,endDate)", argNames = "startDate,endDate") //5
  8. public Object dealSearchDate(ProceedingJoinPoint joinpoint, Date startDate, Date endDate) throws Throwable { //6
  9. Object[] args = joinpoint.getArgs(); //7
  10. if (args[0] == null) {
  11. args[0] = Calendars.getTodayEleven();
  12. args[1] = DateUtils.add(new Date(), 7, TimeUnit.DAYS);//默认显示今天及以后的所有赔率
  13. } else {
  14. args[0] = DateUtils.addHours(startDate, 11);
  15. args[1] = DateUtils.addHours(endDate, 11);
  16. }
  17. return joinpoint.proceed(args); //8
  18. }
  19. }

分别解释一下上面各个地方的意思,标号与语句之后的注释一致

  1. 表示这是一个切面类
  2. 表示这个类是一个配置类,在ApplicationContext启动时会加载配置,将这个类扫描到
  3. 定义一个切点,execution(* com.ronnie.controller.*.list*(java.util.Date,java.util.Date))表示任意返回值,在com.ronnie.controller包下任意类的以list开头的方法,方法带有两个Date类型的参数,args(startDate,endDate)表示需要Spring传入这两个参数
  4. 定义切点的名称
  5. 配置环绕通知
  6. ProceedingJoinPoint会自动传入,用于处理真实的调用
  7. 获取参数,下面代码是修改参数
  8. 使用修改过的参数调用目标类

更多可参考

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()方法即可获取

  1. Signature signature = joinpoint.getSignature();
  2. MethodSignature methodSignature = (MethodSignature) signature;
  3. String[] strings = methodSignature.getParameterNames();
  4. System.out.println(Arrays.toString(strings));

2.通用方法。比较麻烦

  1. public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable{
  2. String classType = joinPoint.getTarget().getClass().getName();
  3. Class<?> clazz = Class.forName(classType);
  4. String clazzName = clazz.getName();
  5. String methodName = joinPoint.getSignature().getName(); //获取方法名称
  6. Object[] args = joinPoint.getArgs();//参数
  7. //获取参数名称和值
  8. Map<String,Object > nameAndArgs = getFieldsName(this.getClass(), clazzName, methodName,args);
  9. System.out.println(nameAndArgs.toString());
  10. //为了省事,其他代码就不写了,
  11. return result = joinPoint.proceed();
  12. }
  1. private Map<String,Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
  2. Map<String,Object > map=new HashMap<String,Object>();
  3. ClassPool pool = ClassPool.getDefault();
  4. //ClassClassPath classPath = new ClassClassPath(this.getClass());
  5. ClassClassPath classPath = new ClassClassPath(cls);
  6. pool.insertClassPath(classPath);
  7. CtClass cc = pool.get(clazzName);
  8. CtMethod cm = cc.getDeclaredMethod(methodName);
  9. MethodInfo methodInfo = cm.getMethodInfo();
  10. CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
  11. LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
  12. if (attr == null) {
  13. // exception
  14. }
  15. // String[] paramNames = new String[cm.getParameterTypes().length];
  16. int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
  17. for (int i = 0; i < cm.getParameterTypes().length; i++){
  18. map.put( attr.variableName(i + pos),args[i]);//paramNames即参数名
  19. }
  20. //Map<>
  21. return map;
  22. }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号