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); } }
参考:
http://kld208.iteye.com/blog/1632935
http://www.oschina.net/code/snippet_201779_53788
原文地址:https://www.cnblogs.com/nickup/p/9219995.html
时间: 2024-11-17 20:47:31