springboot aop 实现自定义注解(demo用到了mybatis-plus 对数据进行操作,所以代码中会有相关的注解)
码云demo:https://gitee.com/dongbingya/springboot
注:只实现该功能,相关方法不做解释说明。
1.首先在pom文件中添加aop依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.日志实体类
@Data
@TableName("systemlog")
public class SystemLog {
@TableField("id")
private String id;
@TableField("title")
private String title;
@TableField("details")
private String details;
@TableField("create_time")
private Date createTime;
@TableField("method")
private String method;
@TableField("error")
private String error;
}
3.自定义注解类
说明:
a.访问修饰符必须为public,不写默认为public;
b.该元素的类型只能是基本数据类型、String、Class、枚举类型、注解类型以及一维数组;
c.该元素的名称一般定义为名词,如果注解中只有一个元素,名字起为value最好;
d.()不是定义方法参数的地方,也不能在括号中定义任何参数,仅仅只是一个特殊的语法;
e.default代表默认值,值必须定义的类型一致;
f.如果没有默认值,代表后续使用注解时必须给该类型元素赋值。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String title() default "";//模块名称
String describe() default "";//描述
}
4.aop切面类。对自定义注解进行功能操作,在这里实现了获取接口方法名等信息并一起添加到日志表中
@Aspect
@Component("logAspect")
public class LogAspect {
@Autowired
private SystemLogMapper systemLogMapper;
private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
// 配置织入点
@Pointcut("@annotation(com.dongbing.demo.modules.system.log.SysLog)")
public void logPointCut() {
}
/**
* 前置通知 用于拦截操作,在方法返回后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "logPointCut()")
public void doBefore(JoinPoint joinPoint) {
handleLog(joinPoint, null);
}
private void handleLog(JoinPoint joinPoint, Exception e) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
SystemLog systemLog = new SystemLog();
//获取方法名
String functionName = signature.getDeclaringTypeName() + "." + signature.getName() + "()";
//获取注解对象
SysLog annotation = signature.getMethod().getAnnotation(SysLog.class);
if(annotation != null){
systemLog.setId(UUID.randomUUID().toString().replace("-", ""));
systemLog.setMethod(functionName);
//获取注解中对方法的描述信息
systemLog.setTitle(annotation.title());
systemLog.setDetails(annotation.describe());
systemLog.setCreateTime(new Date());
if (e != null) {
String err = e.getMessage();
if (err != null && err.length() > 4000) {
err = err.substring(0, 4000);
}
systemLog.setError(err);
}
}
//记录到数据库
systemLogMapper.insert(systemLog);
}
/**
* 是否存在注解,如果存在就获取
*/
private static SysLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(SysLog.class);
}
return null;
}
}
api接口方法上添加自定义的注解,填写相应的信息即可。
@RestController
public class LogController {
//使用日志注解
@SysLog(title = "用户模块",describe = "获取用户列表")
@GetMapping("/sysLogGet")
public String get(){
return "Hello word!";
}
}
6.数据库表字段格式和数据添加到表中后
码云有一些springboot整合的demo