Aspect 加载 自定义注解

自定义注解类

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodCallConstraint {
    //处理器校验必须有值
    String redisKey() default "";
    int countLimit() default 60;
    long time() default 1000;
}

定义Aspect处理类

  • 首先,确定项目spring配置文件中已经存在
<aop:aspectj-autoproxy proxy-target-class="true"/>
  • 其次,处理自定义注解
@Component
@Aspect
public class MethodCallConstraintHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MethodCallConstraintHandler.class);

    /**
     * 定义一个公共的切点
     */
    @Pointcut("@annotation(com.api.web.annotations.MethodCallConstraint)")
    public void MethodCallConstraintPointcut(){
    }

    @Before("MethodCallConstraintPointcut()")
    public void beforeMethod(JoinPoint point){
        Object[] args = point.getArgs();
        LOGGER.info("args :"+ Arrays.toString(args));
        MethodSignature signature = (MethodSignature) point.getSignature();
        LOGGER.info("目标方法为:"+signature.getDeclaringTypeName()+"."+signature.getName());
        Method method = signature.getMethod();
        MethodCallConstraint annotation = method.getAnnotation(MethodCallConstraint.class);
        LOGGER.info("目标注解:"+annotation.redisKey()+","+annotation.countLimit()+","+annotation.time());
    }
// 逻辑代码 ...
}
  • 最后,使用示例
 @MethodCallConstraint(redisKey = "redisValue",countLimit=88,time=666)
    public String product(HttpServletRequest request) throws IOException {
//处理逻辑
}
  • 运行结果日志如下
2017-11-14 17:19:33,282 INFO  c.l.j.c.r.w.a.MethodCallConstraintHandler - [args :[org.apache.catalina.connector.RequestFacade@43fbcc32]]
2017-11-14 17:19:34,901 INFO  c.l.j.c.r.w.a.MethodCallConstraintHandler - [目标方法为:com.le.jr.cash.restapi.web.controller.CashUserController.product]
2017-11-14 17:19:50,730 INFO  c.l.j.c.r.w.a.MethodCallConstraintHandler - [目标注解:redisValue,88,666]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容