闲来无事,查阅资料,学习学习,自定义注解,如何实现
自定义注解
/**
* Description: 自定义日志注解
* Author: WangConvey
* Date: 2021/5/21/021 9:14
* Version: 1.0
*/
@Target({ElementType.METHOD}) // 注解作用地方可以是类、方法、属性字段等
@Retention(RetentionPolicy.RUNTIME) // 有效范围 一般都写 RUNTIME(在运行时有效)
@Documented // 可被 javadoc 识别
public @interface Log {
// 可以理解为注解的自定义属性
String type() default "";
}
AOP实现注解逻辑
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
* Description: 自定义日志注解AOP
* Author: WangConvey
* Date: 2021/5/21/021 9:45
* Version: 1.0
*/
@Slf4j
@Component
@Aspect
public class LogAop {
// 标记自定义注解位置的的方法
@Pointcut("@annotation(com.zjugis.demo.utils.Log)")
public void log() {
}
// 环绕通知 此外还可以是Before、After等
@Around("log()")
public void aroundLog(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
if (method.isAnnotationPresent(Log.class)) {
Log logAnnotation = method.getAnnotation(Log.class);
String type = logAnnotation.type();
// TODO 自己记录日志的逻辑
log.info("-----------Around----------" + type);
} else {
log.warn("-----------Around----------没有使用自定义注解@Log");
}
// 继续执行代码逻辑,没有则自己代码逻辑将不再执行
joinPoint.proceed();
}
}
测试
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description:
* Author: WangConvey
* Date: 2021/5/21/021 10:19
* Version: 1.0
*/
@RestController
@Controller
@RequestMapping("/test")
public class TestController {
@Log // 方法上添加自定义注解
@RequestMapping("/log1")
public void test1() {
}
@Log(type = "debug") // 重写自定义注解的属性值
@RequestMapping("/log2")
public void test2() {
System.out.println("------------------");
}
// 无自定义注解则不会被AOP拦截
@RequestMapping("/log3")
public void test3() {
}
}
到此结束,感谢观看!!!