step1 開啟切面編程
<!-- 開啟切面編程(通過配置織入@Aspectj切面 ) --> <aop:aspectj-autoproxy/>
<aop:aspectj-autoproxy />有一個proxy-target-class屬性,默認為false,表示使用jdk動態代理織入增強,當配為<aop:aspectj-autoproxy poxy-target-class="true"/>時,表示使用CGLib動態代理技術織入增強。不過即使proxy-target-class設置為false,如果目標類沒有聲明接口,則spring將自動使用CGLib動態代理。
step2 編寫日志注解類
@Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface SystemLog { public String description() default ""; }
@Aspect @Component public class SystemLogAspect { @Pointcut("@annotation(com.tj.common.log.system.SystemLog)") public void controllerAspect() {} @Pointcut("@annotation(com.tj.common.log.system.SystemLog)") public void serviceAspect() {} @Pointcut("@annotation(com.tj.common.log.system.SystemLog)") public void repositoryAspect() {} @After("controllerAspect()") public void doBefore(JoinPoint joinPoint) { try { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String ip = request.getRemoteAddr(); String description = getControllerMethodDescription(joinPoint); Object obj = request.getSession().getAttribute("loginUser"); LogUser user = new LogUser(null, null); /*對象obj中必須擁有屬性account、userName*/ BeanUtils.copyProperties(user, obj); if(StringUtils.isBlank(user.getAccount())){ user = new LogUser("Anonymous", "匿名用戶"); } } catch (Exception e) { } } @SuppressWarnings("rawtypes") private static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); String description = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { description = method.getAnnotation(SystemLog.class).description(); break; } } } return description; } }
step2 日志記錄
@CrossOrigin(maxAge = 3600) @RestController @RequestMapping(value = "/cxOrders") public class CxOrderResources { @SystemLog(description="查詢訂單列表操作") @RequestMapping( value="/showData", method = RequestMethod.GET) public ResponseEntity<String> showData()throws ApplicationRuntimeException { return new ResponseEntity<String>("", HttpStatus.OK); } }
參考: