自定义注解

自定义注解

使用场景

Java自定义注解一般使用场景为:自定义注解+拦截器或者AOP,使用自定义注解来自己设计框架,使得代码看起来非常优雅。

自定义注解+拦截器

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{

  String type();

  String secondaryType();
}

注解的处理是通过java反射来处理的。如下,反射相关的类Class, Method, Field都实现了AnnotationElement接口。
在这里插入图片描述应用场景一:自定义注解+拦截器

  1. 实现spring的HandlerInterceptor 类先实现拦截器
public class MyInterceptor implements HandlerInterceptor {
   @Override
   public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    // 反射获取方法上的MyAnnotation 注解
       HandlerMethod handlerMethod = (HandlerMethod)handler;
       MyAnnotation myAnnotation= handlerMethod.getMethod().getAnnotation(MyAnnotation.class);
       if(myAnnotation== null){
           return true;
       }

       // 有MyAnnotation 注解
       response.setContentType("application/json; charset=utf-8");
       response.getWriter().print("你访问的资源xxxx");
       return false;
   }

   @Override
   public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

   }

   @Override
   public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

   }
}
  1. 实现spring类WebMvcConfigurer,创建配置类把拦截器添加到拦截器链中
public class MyInterceptorConfigurer implements WebMvcConfigurer {
   @Override
   public void addInterceptors(InterceptorRegistry interceptorRegistry) {
       interceptorRegistry.addInterceptor(new SourceAccessInterceptor()).addPathPatterns("/**");
   }

自定义注解+AOP 实现日志打印

链接: 快给我饭吃的《Java 自定义注解及使用场景》

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值