教程以实现日志记录为基础
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
首先你得有依赖
然后来一个注解类
//可使用此注解的 obj(对象,这里是方法)
@Target(ElementType.METHOD)
//用来说明该注解类的生命周期-运行时
@Retention(RetentionPolicy.RUNTIME)
//标记为注解
@Documented
public @interface SysLog {
String value() default "";
}
最后动态代理一下
@Aspect
@Component
public class SysLogAspect {
@Autowired
private SysLogService sysLogService;
//就是上面那个注解类的位置
@Pointcut("@annotation(com.**.**.annotation.SysLog)")
public void logPointCut() {
}
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
//执行时长(毫秒)
long executeTime = System.currentTimeMillis() - beginTime;
//保存日志
saveSysLog(point, executeTime);
return result;
}
private void saveSysLog(ProceedingJoinPoint joinPoint, long executeTime) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLogEntity mySysLog = new SysLogEntity();
SysLog syslog = method.getAnnotation(SysLog.class);
if(syslog != null){
//注解上的描述
mySysLog.setOperation(syslog.value());
}
//className
String className = joinPoint.getTarget().getClass().getName();
//请求的方法名
String methodName = signature.getName();
mySysLog.setMethod(className + "." + methodName + "()");
//请求的参数
Object[] args = joinPoint.getArgs();
try{
String params = new Gson().toJson(args[0]);
mySysLog.setParams(params);
}catch (Exception e){
}
//获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//设置IP地址
mySysLog.setIp(IPUtils.getIpAddr(request));
mySysLog.setTime(executeTime);
mySysLog.setCreateDate(new Date());
//保存系统日志
sysLogService.save(mySysLog);
}
大功告成, 在需要日志记录的方法(一般为service层)上面注解个 @SysLog 就可以了,很简单, 如果发现没报错, 死活就是不能成功, 那你的service一般都是被springmvc扫描到了,springMVC会先扫描加载,当springMVC扫描后,扫描过的部分,spring就不会去扫描了,于是spring中的AOP就不能发挥作用了
当然我用的是springboot 没有出现这个问题