基于Springboot利用SpringAOP切面及自定义注解 记录每次操作记录
Springboot相对于SSM更加的简便,因为好多自动帮我们装配了
1,定义注解
package com.zyd.blog.business.annotation;
import java.lang.annotation.*;
//定义系统日志系统类注解
//注解的作用目标
@Target(ElementType.METHOD)
//注解的保留策略
@Retention(value = RetentionPolicy.RUNTIME) //注解的保留策略
//
@Documented
public @interface SysLog {
String value() default "";
}
2,定义切面
package com.zyd.blog.business.aspect;
import com.google.gson.Gson;
import com.zyd.blog.business.service.SysLogService;
import com.zyd.blog.persistence.beans.SysLog;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.utils.IPUtils;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
/**
* 系统日志
* 切面处理类
*/
@Aspect//定义切面类
@Component
public class SysLogAspect {
@Autowired
private SysLogService logService;
//切点连接点
//指向自定义注解路径
/* @Pointcut("@annotation(com.zyd.blog.business.annotation.SysLog)")
public void logPointCut(){}
*/
@Before("@annotation(com.zyd.blog.business.annotation.SysLog)")
public Object before(){
System.out.println("调用方法之前");
return null;
}
@After("@annotation(com.zyd.blog.business.annotation.SysLog)")
public Object after(){
System.out.println("调用方法之后");
return null;
}
@Around("@annotation(com.zyd.blog.business.annotation.SysLog)")
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println("调用方法之中!");
long beginTime = System.currentTimeMillis();
//执行方法
Object result = point.proceed();
long time = System.currentTimeMillis() - beginTime;
System.out.println(result+" --执行时间为:"+time);
//保存日志
saveSysLog(point, time);
return result;
}
private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog sysLog = new SysLog();
/*
SysLog syslog = (SysLog) method.getAnnotation(SysLog.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 = new Gson().toJson(args[0]);
// sysLog.setParams(params);
}catch (Exception e){
}
/* //获取request
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
//设置IP地址
sysLog.setIp(IPUtils.getIpAddr(request));
//用户名
String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
sysLog.setUsername(username);
sysLog.setTime(time);
sysLog.setCreateDate(new Date());
//保存系统日志
sysLogService.save(sysLog);*/
}
}这样就大功告成了,注解打在controller的方法即可
- 本文标签: SpringBoot
- 版权声明: 本站原创文章,于2019年02月19日由好好网发布,转载请注明出处