- 在pom.xml中添加相关的依赖(参考pom.xml文件)
- 在applicationContext.xml中进行相关的配置(参考applicationContext.xml)
@Component@Aspectpublic class LogAop { @Autowired private HttpServletRequest request; @Autowired private ISysLogService sysLogService; //访问时间 private Date startTime; //访问的类 private Class executionCla; //访问的方法 private Method executionMethod; @Before("execution(* com.deya.controller.*.*(..))") public void doBefore(JoinPoint joinPoint) throws NoSuchMethodException { startTime = new Date(); executionCla = joinPoint.getTarget().getClass(); String methodName = joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); if (args==null||args.length==0){ //只能获取无参数方法 executionMethod = executionCla.getMethod(methodName); }else{ Class[] classArgs = new Class[args.length]; for(int i=0;i<args.length;i++){ classArgs[i] = args[i].getClass(); } executionMethod = executionCla.getMethod(methodName,classArgs); } } @After("execution(* com.deya.controller.*.*(..))") public void doAfter(JoinPoint joinPoint) throws Exception { String url; String ip; if(executionCla!=null&&executionMethod!=null&&executionCla==LogAop.class){ RequestMapping classAnnotation = (RequestMapping) executionCla.getAnnotation(RequestMapping.class); if(classAnnotation!=null){ String[] classValue = classAnnotation.value(); //获取方法上的@RequestMapping RequestMapping methodAnnotation = executionMethod.getAnnotation(RequestMapping.class); String[] methodValue = methodAnnotation.value(); url=classValue[0]+methodValue[0]; ip = request.getRemoteAddr(); // 获取当前操作的用户 // 从上下文中获得当前登录的用户 SecurityContext context = SecurityContextHolder.getContext(); User user = (User) context.getAuthentication().getPrincipal(); String username = user.getUsername(); SysLog sysLog = new SysLog(); Long executionTime = new Date().getTime()-startTime.getTime(); sysLog.setExecutionTime(executionTime); sysLog.setIp(ip); sysLog.setVisitTime(new Date(executionTime)); sysLog.setUrl(url); sysLog.setUsername(username); sysLog.setMethod("[类名]"+executionCla.getName()+"[方法名]"+executionMethod.getName()); sysLogService.save(sysLog); } } }}