元注解
元注解用来在声明新注解时指定新注解的一些特性
@Target 指定新注解标注的位置,比如类、字段、方法等,取值有ElementType.Method等
@Retention 指定新注解的信息保留到什么时候,取值有RetentionPolicy.RUNTIME等
@Inherited 指定新注解标注在父类上时可被子类继承
常用注解
@Target(ElementType.METHOD) // 指定新注解可以标注在方法上
@Retention(RetentionPolicy.RUNTIME) // 指定新注解保留到程序运行时期
@Inherited // 指定新注解标注在父类上时可被子类继承
注解Target
TYPE:类、接口(包括注解类型)和枚举的声明
FIELD:字段声明(包括枚举常量)
METHOD:方法声明
PARAMETER:参数声明
CONSTRUCTOR:构造函数声明
LOCAL_VARIABLE:本地变量声明
ANNOTATION_TYPE:注解类型声明
PACKAGE:包声明
TYPE_PARAMETER:类型参数声明,JavaSE8引进,可以应用于类的泛型声明之处
TYPE_USE:JavaSE8引进,此类型包括类型声明和类型参数声明
编写自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CPCurrentLimit {
//水边设置两个属性 有需要可以自己另外添加
String name() default "";
double token() default 20;
}
编写aop
@Aspect
@Component
public class CpCurrentLimitAop {
/**
* 每秒生成1.0个令牌
* //
*/
private ConcurrentHashMap<String, RateLimiter> rateLimiters = new ConcurrentHashMap<>();
@Around(value = "@annotation(com.mayikt.service.annotation.CPCurrentLimit)")
public Object around(ProceedingJoinPoint joinPoint) {
//获取拦截的方法
Signature signature = joinPoint.getSignature();
//获取该方法上的注解
MethodSignature methodSignature = (MethodSignature) signature;
CPCurrentLimit cpCurrentLimit = methodSignature.getMethod().getDeclaredAnnotation(CPCurrentLimit.class);
// 获取到该注解的name
String name = cpCurrentLimit.name();
// 获取该注解的token
double token = cpCurrentLimit.token();
System.out.println("name:"+name+"token"+token);
try {
Object proceedResult = joinPoint.proceed(); //执行目标方法
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
编写视图层
@GetMapping("/cc")
@CPCurrentLimit(name = "add", token = 10)
public String addcc() {
return "my is add";
}