JDK1.5中引入注解,spring框架把java注解发扬光大

一  创建自定义注解

  

import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy; @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
String value() default "";
}

二  解析注解

使用@Aspect注解使得该类成为切面类

import java.lang.reflect.Method;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import com.prostate.common.service.LogService;
import com.prostate.system.domain.UserToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import com.prostate.common.annotation.Log;
import com.prostate.common.dao.LogDao;
import com.prostate.common.domain.LogDO;
import com.prostate.common.utils.HttpContextUtils;
import com.prostate.common.utils.IPUtils;
import com.prostate.common.utils.JSONUtils;
import com.prostate.common.utils.ShiroUtils;
import com.prostate.system.domain.UserDO; @Aspect
@Component
public class LogAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class); @Autowired
LogService logService; @Pointcut("@annotation(com.common.annotation.Log)")
public void logPointCut() {
} @Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
// 执行方法
Object result = point.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
//异步保存日志
saveLog(point, time);
return result;
} void saveLog(ProceedingJoinPoint joinPoint, long time) throws InterruptedException {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogDO sysLog = new LogDO();
Log syslog = method.getAnnotation(Log.class);
if (syslog != null) {
// 注解上的描述
sysLog.setOperation(syslog.value());
}
// 请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
sysLog.setMethod(className + "." + methodName + "()");
// 请求的参数
Object[] args = joinPoint.getArgs();
try {
String params = JSONUtils.beanToJson(args[0]).substring(0, 4999);
sysLog.setParams(params);
} catch (Exception e) { }
// 获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
// 设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
// 用户名
UserDO currUser = ShiroUtils.getUser();
if (null == currUser) {
if (null != sysLog.getParams()) {
sysLog.setUserId(-1L);
sysLog.setUsername(sysLog.getParams());
} else {
sysLog.setUserId(-1L);
sysLog.setUsername("获取用户信息为空");
}
} else {
sysLog.setUserId(ShiroUtils.getUserId());
sysLog.setUsername(ShiroUtils.getUser().getUsername());
}
sysLog.setTime((int) time);
// 系统当前时间
Date date = new Date();
sysLog.setGmtCreate(date);
// 保存系统日志
logService.save(sysLog);
}
}

通过@Pointcut指定切入点,这里指定Log注解,也就是被@Log修饰的方法,进入该切入点

①  @Before  前置通知 在某连接点之前执行的通知

②   @Around  环绕通知 在实现方法的前后执行的通知

③   @AfterReturning 后置通知  在某连接点正常完成执行的通知

④   @AfterThrowing  异常通知  在方法抛出异常退出执行的通知

⑤   @After  后置通知

@RequiresPermissions("base:scaleManager:edit")
@Log("编辑题目或选项")
@GetMapping("/edit/{id}")
String edit(Model model, @PathVariable("id") String id) {
ScaleDO scaleDO = scaleManagerService.get(id);
model.addAttribute("scaleDO", scaleDO);
ScaleDO scale = scaleManagerService.get(scaleDO.getParentId());
model.addAttribute("scale",scale);
return prefix+"/edit";
}

随便弄一个测试类就可测试了

Spring自定义日志注解的更多相关文章

  1. 自定义日志注解 + AOP实现记录操作日志

      需求:系统中经常需要记录员工的操作日志和用户的活动日志,简单的做法在每个需要的方法中进行日志保存操作, 但这样对业务代码入侵性太大,下面就结合AOP和自定义日志注解实现更方便的日志记录   首先看 ...

  2. springboot最新版本自定义日志注解和AOP

    LogAspectAnnotation @ControllerLogAspectAnnotation /** * * Define a log facet annotation * @author s ...

  3. Spring Boot @Enable*注解源码解析及自定义@Enable*

      Spring Boot 一个重要的特点就是自动配置,约定大于配置,几乎所有组件使用其本身约定好的默认配置就可以使用,大大减轻配置的麻烦.其实现自动配置一个方式就是使用@Enable*注解,见其名知 ...

  4. 【Redis】redis异步消息队列+Spring自定义注解+AOP方式实现系统日志持久化

    说明: SSM项目中的每一个请求都需要进行日志记录操作.一般操作做的思路是:使用springAOP思想,对指定的方法进行拦截.拼装日志信息实体,然后持久化到数据库中.可是仔细想一下会发现:每次的客户端 ...

  5. spring统一日志管理,切面(@Aspect),注解式日志管理

    step1 开启切面编程 <!-- 开启切面编程(通过配置织入@Aspectj切面 ) --> <aop:aspectj-autoproxy/> <aop:aspectj ...

  6. Spring Boot 自定义日志详解

    本节内容基于 Spring Boot 2.0. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spring Boot 开启的 2 种方式 Spring ...

  7. 使用Spring自定义注解实现任务路由的方法

    在Spring mvc的开发中,我们可以通过RequestMapping来配,当前方法用于处理哪一个URL的请求.同样我们现在有一个需求,有一个任务调度器,可以按照不同的任务类型路由到不同的任务执行器 ...

  8. 深入Spring:自定义注解加载和使用

    前言 在工作中经常使用Spring的相关框架,免不了去看一下Spring的实现方法,了解一下Spring内部的处理逻辑.特别是开发Web应用时,我们会频繁的定义@Controller,@Service ...

  9. spring:自定义限定符注解@interface, 首选bean

    spring:自定义限定符注解@interface, 首选bean 1.首选bean 在声明bean的时候,通过将其中一个可选的bean设置为首选(primary)bean能够避免自动装配时的歧义性. ...

随机推荐

  1. 【linux】【elasticsearch】docker部署elasticsearch及elasticsearch-head

    前言 Elasticsearch是一个基于Apache Lucene(TM)的开源搜索引擎.无论在开源还是专有领域,Lucene可以被认为是迄今为止最先进.性能最好的.功能最全的搜索引擎库.但是,Lu ...

  2. python unittest+parameterized,单元测试框架+参数化

    总要写新的自动化测试模块,在这里把demo记录下来,后面方便自己直接复制粘贴 from nose_parameterized import parameterized import unittest ...

  3. event.stopPropagation()、event.preventDefault()与return false的区别

    做小demo时经常用到return false来取消默认事件,但一直不是很懂它和preventDefault()等的区别,今天查了查文档和大神们的博客,在这里对相关知识点做一个总结 首先开门见山,总结 ...

  4. sublime_REPL使用及安装教程(解决Sublime无交互问题)

    谈到python编程工具能想到那些? pycharm?IDLE? Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等,还可自定义键绑定,菜单和工具栏. ...

  5. 心动吗?正大光明的免费使用IntelliJ IDEA商业版

    IntelliJ IDEA是广受Java开发者喜爱的工具,其商业版的价格十分昂贵,如下图: 现在有机会免费获取IntelliJ IDEA的正版License,您是否心动呢?我把自己成功申请Licens ...

  6. SpringBootSecurity学习(10)网页版登录之记住我功能

    场景 很多登录都有记住我这个功能,在用户登陆一次以后,系统会记住用户一段时间,在这段时间,用户不用反复登陆就可以使用我们的系统.记住用户功能的基本原理如下图: 用户登录的时候,请求发送给过滤器User ...

  7. Hadoop点滴-初识MapReduce(1)

    分析气候数据,计算出每年全球最高气温(P25页) Map阶段:输入碎片数据,输出一系列“单键单值”键值对 内部处理,将一系列“单键单值”键值对转化成一系列“单键多值”键值对 Reduce阶段,输入“单 ...

  8. leveldb 源码--总体架构分析

    一 本文目的 对leveldb的总体设计框架分析(关于leveldb基本原理,此文不做阐述,读者可以自行检索文章阅读即可),对leveldb中底层数据存储数据格式,内存数据模型,compact,版本管 ...

  9. CSS 换行

    默认情况下,元素的属性是 white-space:normal:自动换行:(不把单词截断,会把单词看作一个整体) -----但是但是但是但是..当元素中的内容是一对没有空格的字符/数字时,超过容器宽度 ...

  10. Spring Boot (八): Mybatis 增强工具 MyBatis-Plus

    1. 简介 在上一篇文章<Spring Boot (七): Mybatis极简配置> 中我们介绍了在 Spring Boot 中 Mybatis 的基础使用方式,其中有一部分美中不足的是 ...