注解的意思写在上一篇文章(笔记,给自己记录)
先创建一个注解类(简单点就写个title,可以写很多字段描述)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Mytest {
String title() default "";
}
做一个切面,来使用这个注解(也可以在filter中判断,使用)切面的注解之前的文章可以翻出来看
@Aspect
@Component
public class MytestAspect {
private static final Logger log = LoggerFactory.getLogger(MytestAspect.class);
// 配置织入点
@Pointcut("@annotation(com.xxx.xxxx.Mytest)")
public void MytestPointCut() {
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "MytestPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
{
handleLog(joinPoint, null, jsonResult);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult)
{
try {
// 获得注解
Mytest annotationLog = getAnnotationLog(joinPoint);
if (annotationLog == null)
{
return;
}
//获取注解信息
String title = annotationLog.title();
//打印一下
log.debug("============title信息:{}", title);
//获取用户信息(这个是登录的时候设置的)
Long currentUserId = UserUtil.getCurrentUserId();
//获取到注解上面的信息就可以插进日志表了
}catch (Exception ex){
}
}
/**
* 是否存在注解,如果存在就获取
*/
private Mytest getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(Mytest.class);
}
return null;
}
}
然后再需要加上日志的请求的方法加上这个注解
@Mytest(title = "首页轮播图")
@GetMapping("listImg")
public Result<List<IndexImg>> listImg(){
return new Result<List<IndexImg>>().ok(rbListService.listImg());
}
请求一下,看看打印结果
2020-01-08 15:15:27.115 DEBUG 8624 --- [nio-8989-exec-1] com.xxx.xxx.utils.MytestAspect : ============title信息:首页轮播图
另外还可以获取当前注解的方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();