这篇文章将为大家详细讲解有关Spring Aop之AspectJ注解配置如何实现日志管理,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
最近项目要做一个日志功能,我用Spring Aop的注解方式来实现。
创建日志注解
package com.wyj.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 日志注解
*
*
* @author:WangYuanJun
* @date:2016年8月26日 下午8:25:35
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
String action() default "";//动作
}
创建切面通知类
记录操作的方法名,参数和花费的时间,使用环绕通知
package com.wyj.aspect;
import java.lang.reflect.Method;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wyj.annotation.SysLog;
import com.wyj.entity.SysLogEntity;
import com.wyj.service.SysLogService;
/**
* 日志切面通知
*
*
* @author:WangYuanJun
* @date:2016年8月26日 下午10:28:57
*/
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
/**
* 切入点
*/
@Pointcut("@annotation(com.wyj.annotation.SysLog)")
public void pointCut() {}
/**
* 环绕通知
*
* @param joinPoint
* @return
* @throws Throwable
*/
@Around("pointCut()")
public Object aroud(ProceedingJoinPoint joinPoint) throws Throwable {
// 开始时间
long beginTime = System.currentTimeMillis();
// 执行目标方法
Object result = joinPoint.proceed();
// 执行时长(毫秒)
long time = System.currentTimeMillis() - beginTime;
// 保存日志
saveSysLog(joinPoint, time);
return result;
}
/**
* 保存日志
*
* @param joinPoint
* @param time
*/
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLogEntity sysLogEntity = new SysLogEntity();
SysLog sysLog = method.getAnnotation(SysLog.class);
if (sysLog != null) {
// 注解上的描述
sysLogEntity.setOperation(sysLog.action());
}
// 获取目标类名
String className = joinPoint.getTarget().getClass().getName();
// 获取方法名
String methodName = signature.getName();
sysLogEntity.setMethod(className + "." + methodName + "()");
// 请求的参数
Object[] args = joinPoint.getArgs();
if (args != null && args.length != 0 && args[0] != null) {
sysLogEntity.setParams(args[0].toString());
}
sysLogEntity.setTime(time);
// 保存系统日志
sysLogService.save(sysLogEntity);
}
}
扫描和启动aop注解
日志注解的应用
效果
关于“Spring Aop之AspectJ注解配置如何实现日志管理”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。