如何使用Spring AOP預處理Controller的參數
實際編程中,可能會有這樣一種情況,前臺傳過來的參數,我們需要一定的處理才能使用
比如有這樣一個Controller@Controllerpublic 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點,如果只有這么一個類的話,我們是可以直接在方法最前面處理就可以了
但是,還有下面兩個類具有同樣的業務邏輯@Controllerpublic 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); }}
@Controllerpublic 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 //2public 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 { //6Object[] args = joinpoint.getArgs(); //7if (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));
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;}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
