annotation修饰调用参数

在项目里面想使用自定义annotation,就是参数列表,类似于spring mvc里面的 @PathVariable("id") 注解。然后再使用AOP来解释这个注解。

1) 开始添加springboot aop依赖,

	  <dependency>
		  <groupId>org.springframework.boot</groupId>
		  <artifactId>spring-boot-starter-aop</artifactId>
	  </dependency>

 开启使用aspect

@EnableAspectJAutoProxy

2) 声明注解,

 

  第一个声明的注解作用在方法上,只有这个方法的才会去扫描。

@Inherited
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {

    String name();
    int rate();
    int period();
    TimeUnit periodUnit() default TimeUnit.SECONDS;

}

 第二个注解声明在参数上,只有这个方法的参数上才可以生效。

@Inherited
@Documented
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimitKey {

    String value();
}

3) 注解方法

    @Around(value = "@annotation(RateLimiter)")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time = System.currentTimeMillis();

        //得到方法的信息
        MethodSignature methodSignature = (MethodSignature)pjp.getSignature();

        //获得方法注解的信息
        RateLimiter configruation = methodSignature.getMethod().getAnnotation(RateLimiter.class);
        System.out.println(configruation.confBeanName());

        Object retVal = pjp.proceed();
        time = System.currentTimeMillis() - time;
        System.out.println("process time: " + time + " ms");
        return retVal;
    }

    //获得在参数上面的注解信息
    private Object getAnnotateObject(Object[] objects, Method method){

        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters){
            if (parameter.isAnnotationPresent(RateLimitKey.class)){
                RateLimitKeykey = parameter.getAnnotation(RateLimitKey.class);
                System.out.println(key.value());
            }
        }

        return null;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值