1. 定义注解
注解标志:@interface
常用元注解(定义在注解上的注解)
// 注解的生命周期 RUNTIME > Source > CLASS
@Retention(RetentionPolicy.RUNTIME)
//枚举类:
//TYPE 作用在类 接口上; METHOD 作用在方法上
@Target({ElementType.METHOD})
@Inherited //可以被继承
@Documented // 可以被写入javaDoc中
public @interface JsonVerify {
// 这里面的属性要加 括号 同时只支持8大数据类型 以及其数组类型
// 以及 Class
String key() default "";
}
2. 实现注解的方法
2.1 使用切面
// 在类上定义注解@Aspect
@Aspect
@Component
@Slf4j
public class JsonVerifyAspect {
// 配置织入点(切点)
@Pointcut("@annotation(org.springblade.sdm.annotation.JsonVerify)")
public void verifyPointCut()
{
}
// 常用切面@Before 方法前 @After 方法后 @Around 环绕方法
@Before("verifyPointCut()")
@SneakyThrows
public void before(JoinPoint joinPoint){
log.info("--------校验json---------");
// 获取注解
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
Method method = methodSignature.getMethod();
JsonVerify jsonVerify = method.getAnnotation(JsonVerify.class);
//获取第一个参数
Object obj = joinPoint.getArgs()[0];
// 如果是环绕Around 则在程序中使用 joinPoint.proceed(); 继续执行被注解的方法
}
}
注意事项
无法注入的问题
如果在方法上使用注解,要保证该方法并不是被本类中其它方法调用,
否则AOP无法动态代理此类,需要加载本类(WHY? 待定)
// 使用懒加载
@Lazy
@Autowired
CurrentService currentService = THIS;
// 调用
THIS.方法名