1.面向切面編程(AOP)Aspect Oriented Programming。
切面編程的目的是為了把通用邏輯從業務邏輯分離出來。
作為一個Java開發,基本是離不開spring的,spring 的核心基礎功能就是Ioc和Aop。
這里我的應用是打印接口請求的URL、IP、請求方式以及入參,方便接口調試。
2.代碼如下,拷貝可以直接使用,很方便。沒基礎的同學,請自己先行補充理論知識。
@Aspect @Component public class ParamLogAspect { private static final Logger logger = LoggerFactory.getLogger(ParamLogAspect.class); /** * 定義一個切點 * 切入 controller包 * api包 * commonInterface.controller * commonInterface.service.impl * 下的所有類的所有方法 */ @Pointcut("execution(* com.meritdata.cloud.shellmiddleplatform.dataservice.fourInOne.controller.*.*(..))" + "||execution(* com.meritdata.cloud.shellmiddleplatform.dataservice.fourInOne.api.*.*(..)) " + "||execution(* com.meritdata.cloud.shellmiddleplatform.dataservice.fourInOne.commonInterface.controller.*.*(..)) ") public void validateMethod(){ } @Before("validateMethod()") public void validate(JoinPoint joinPoint){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); logger.info("=====URL : " + request.getRequestURL().toString()); logger.info("=====IP : " + request.getRemoteAddr()+" HTTP_METHOD :" + request.getMethod()); StringBuffer body = new StringBuffer(); Object[] arguments = joinPoint.getArgs(); //獲取方法的參數 if(arguments.length!=0){ try { Map<String, Object> params = params = (Map<String, Object>)arguments[0]; for (String key:params.keySet() ) { body.append(key).append(":").append(params.get(key)).append(";"); } if(body.toString().length()==0){ logger.info("body參數為空!"); }else { logger.info("=====方法接收參數[{}]",body.toString().substring(0,body.toString().length()-1)); } }catch (Exception ex){ logger.info("=====方法接收參數[{}]",arguments[0].toString()); } } //獲取問號拼接的參數: Enumeration<String> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String paraName = (String) enu.nextElement(); if (!StringUtils.isEmpty(request.getParameter(paraName))) { logger.info("=====問號后param : " + paraName + " : " + request.getParameter(paraName)); } } } }