注解类:
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperLog {
String operDesc() default ""; //操作说明
String tableName() default ""; // 操作表名
}
切面:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Aspect
@Component
public class OperLogAspect {
@Autowired
GDataConnectMapper dataConnectMapper;
@Autowired
TokenService tokenService;
@Autowired
GDataLogMapper dataLogMapper;
/**
* 切点,Pointcut指向自定义注解
*/
@Pointcut("@annotation(com.ruoyi.project.croplanddb.annotation.OperLog)")
public void operLogPoinCut(){
}
/**
* 返回通知,这里的@annotation()用来接收自定义注解参数值
* 格式必须为"切点&&@annotation(注解名)"
* 并且方法参数中的名称要和@annotation中的注解名完全相同
* JoinPoint用来获取返回参数、类名、方法名、注解等,不过此处注解使用的是@annotation获取
* 注意:JoinPoint一定要写在参数的第一位
*/
@AfterReturning(value = "operLogPoinCut()&&@annotation(operLog)")
public void doAfterReturning(JoinPoint joinpoint, OperLog operLog) throws Exception {
//保存日志
saveOperLog(joinpoint,operLog);
}
/**
* 保存日志
* @param joinpoint
* @param log
* @throws Exception
*/
private void saveOperLog(JoinPoint joinpoint, OperLog log) throws Exception {
//joinpoint中拿到参数
//此处拿到的是加注解方法的返回值
//获取方法名:joinPoint.getSignature().getName()
Object arg = joinpoint.getArgs()[0];
GDataConnect dataConnect = null;
//连接信息
if (arg instanceof GDataConnect){
GDataConnect dataConn = (GDataConnect) arg;
dataConnect = dataConnectMapper.selectById(dataConn.getId());
} else if (arg instanceof Integer){
Integer connId = (Integer) arg;
dataConnect = dataConnectMapper.selectById(connId);
}
//保存日志
GDataLog dataLog = new GDataLog();
dataLog.setDel("1");
//当前登录用户
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
try {
SysUser user = tokenService.getLoginUser(request).getUser();
dataLog.setUserId(user.getUserId().intValue());
dataLog.setUserName(user.getUserName());
}catch (Exception e){
throw new IllegalArgumentException("用户未登录");
}
if (dataConnect != null){
//当前主机的ip地址
dataLog.setConnIp(request.getRemoteAddr());
dataLog.setConnDatabase(dataConnect.getDatabaseName());
//保存操作信息
String logOperDesc = dataConnect.getConnIp() + "连接,表" + log.tableName() + log.operDesc() + "," + log.operDesc() + "表id:" + dataConnect.getId();
dataLog.setOperDesc(logOperDesc);//自定义注解备注
dataLog.setCreateTime(new Date());
dataLogMapper.insertGDataLog(dataLog);
}
}
}
加注解使用:
@PostMapping("/add")
@OperLog(operDesc = "新增",tableName = "g_data_connect")
public Result addDaraConnect(@RequestBody GDataConnect dataConn, HttpServletRequest request){
//业务逻辑
}
此代码存在只有返回指定类型才可用的弊端。