分享

SpringAop--系统日志简例

 余香阁 2021-05-27

        通过Spring的Aop我们可以声明式的配置事务管理,那么同样可以通过SpringAop来进行处理的系统日志该如何实现呢?

一、数据表和实体类的准备

我们要管理系统日志,那么数据表和实体类是必不可少的,这里编写一个简单的实体类:

/** * 系统日志实体类 * * @author Mr.song * @date 2019/05/09 17:57 */public class SysLog implements Serializable {
private String id; private String userName; private String ip; private Date time; private String method;//访问的方法名称 private String action;//进行的操作名称 //...}

同时我们还要完成Dao层和Service层相应的添加、查询方法。(比较简单,这里忽略)

二.编写日志通知的切面类

这里采用基于注解的环绕通知

/** * 用于记录日志的通知 * * @author Mr.song * @date 2019/05/09 19:50 */@Aspect //声明为切面类@Componentpublic class LogAspect {
@Autowired private SysLogService sysLogService; @Autowired private HttpSession session; @Autowired private HttpServletRequest request;
@Around("execution(* cn.dintalk.web.controller.*.*.*(..))") public Object aroundSysLog(ProceedingJoinPoint pjp) { try { //获取到切入点的签名 Signature signature = pjp.getSignature(); //将签名转为方法的签名 if (signature instanceof MethodSignature) { MethodSignature ms = (MethodSignature) signature; //获取方法 Method method = ms.getMethod(); //获取注解(判断是否为RequestMapping类型的) if (method.isAnnotationPresent(RequestMapping.class)) { //创建日志对象 SysLog sysLog = new SysLog(); //设置日志的操作方法和名称 sysLog.setMethod(method.getName()); //获取方法上的注解,设置日志的操作名称 RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); sysLog.setAction(requestMapping.name()); //设置日志的用户相关信息 User user = (User) session.getAttribute("user"); if (user == null || UtilFuns.isEmpty(user.getUserName())) { //匿名访问 sysLog.setUserName("匿名"); } else { sysLog.setUserName(user.getUserName()); } //设置日志的ip和时间 sysLog.setTime(new Date()); sysLog.setIp(request.getRemoteAddr()); //添加日志 sysLogService.add(sysLog); } } //获取当前切入点方法的所需参数 Object[] args = pjp.getArgs(); //执行方法并返回 Object obj = pjp.proceed(args); return obj; } catch (Throwable e) { throw new RuntimeException(e); } }}

Tips: 要注意在配置文件中开启对注解切面的支持

<!-- 开启切面注解支持 --> <aop:aspectj-autoproxy/>

Tips :  由于日志需要具体的操作名称,因此我们的Controller中的方法上的注解就需要为该操作起名称。如(name="查看用户列表"):

//展示用户列表@RequestMapping(value = "/list",name = "查看用户列表")public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size){ //1.查询到企业下用户的分页数据 PageInfo pageInfo = userService.findAll(companyId, page, size); //2.保存到域中进行转发 request.setAttribute("page",pageInfo); return "system/user/user-list";}

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多