1.在springMvc的xml配置文件中加入开启aop和扫描aop的配置
<!-- 把aop配置类加入bean容器中 --> <context:component-scan base-package="com.sinosoft.aop"></context:component-scan> <!-- 开启aop注解方式 --> <aop:aspectj-autoproxy/>
2.编写aop类
@Aspect @Configuration public class Logger { @Autowired private OperatorLogService service; @Autowired HttpServletRequest request; @Autowired HttpServletResponse response; @Pointcut("@within(org.springframework.stereotype.Controller) || @within(org.springframework.web.bind.annotation.RestController)") public void cutController() { } @Around("cutController()") public Object recordSysLog(ProceedingJoinPoint joinPoint) throws Throwable { OperatorLogDTO dto = new OperatorLogDTO(); String flag = "Y"; Object ob = null; String url = request.getRequestURI(); //String url=request.getRequestURL().toString(); int length = request.getContextPath().length(); url = url.substring(length); UserInfo userInfo = CurrentUser.getCurrentUser(); try { ob = joinPoint.proceed(); } catch (Throwable throwable) { // 没个对数据库进行操作的方法中都存在try catch,因为这里存在这个问题存在了异常也无法执行异常通知(异常在之前就被处理了) // 解决方法:所有catch中都把异常抛出 flag = "N"; // 这里不抛出这个异常全局异常时捕获不到任何异常的,aop在全局异常前执行,所有只有抛出此异常全局异常才能获取到 throw throwable; } finally { // 用户登录后才会执行 if (userInfo != null) { dto.setOperateResult(flag); // 获取用户的code dto.setUserCode(userInfo.getUserCode()); // 获取客户端ip dto.setOperatorIp(request.getRemoteHost()); // 获取请求路径 dto.setInterfaceValue(url); service.add(dto); } } return ob; } }