自定义注解+aop做日志记录
自定义一个注解:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CommitLog {
/**
* 类型名称
* @return
*/
String typeName() ;
/**
* 方法操作类型
* @return
*/
String methodName();
}
定义一个日志切面,写入日志信息:
/**
* 日志切面
*/
@Aspect
@Slf4j
@Component
public class LogAspect {
//切点
@Pointcut("@annotation(com.example.demo3.log.CommitLog)")
public void PointCut(){
}
@Around("LogAspect.PointCut()")
public Object methodLogAround(ProceedingJoinPoint proceedingJoinPoint) {
MethodSignature signature = (MethodSignature)proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
String className = method.getDeclaringClass().getName();// 类名称
String methodName = method.getName(); // 方法名称
Object[] args = proceedingJoinPoint.getArgs();//参数
// 获取注解信息
CommitLog commitLog=method.getAnnotation(CommitLog.class);
String key = commitLog.codeKey();
String type = commitLog.type();
// 调用前
log.info("类名称:{},方法名称{},入参{},注解信息{}",className,methodName,args,commitLog);
try {
Object proceed = proceedingJoinPoint.proceed(args);
} catch (Throwable e) {
// e.printStackTrace();
log.info("切面异常");
}
// 调用后
log.info("调用前");
//
//数据库写入
logMapper.insert(logInfo);
return new Object();
}
}
提供对外接口,并使用自定义注解:
@Controller
public class UserController {
@GetMapping("/update")
@CommitLog(codeKey = "key1",type = "update")
public void update(){
System.out.println("1234567890");
}
@GetMapping("/select")
@CommitLog(codeKey = "key2",type = "select")
public void select(){
System.out.println("1234567890");
}
}
用于记录,学习。

浙公网安备 33010602011771号