Spring自定义注解的示例分析

发布时间:2021-08-04 14:09:23 作者:小新
来源:亿速云 阅读:126

这篇文章主要介绍Spring自定义注解的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

字段注解

字段注解一般是用于校验字段是否满足要求,hibernate-validate依赖就提供了很多校验注解 ,如@NotNull、@Range等,但是这些注解并不是能够满足所有业务场景的。比如我们希望传入的参数在指定的String集合中,那么已有的注解就不能满足需求了,需要自己实现。

自定义注解

定义一个@Check注解,通过@interface声明一个注解

@Target({ ElementType.FIELD}) 
//只允许用在类的字段上
@Retention(RetentionPolicy.RUNTIME) 
//注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解
@Constraint(validatedBy = ParamConstraintValidated.class)
public @interface Check {
  /**
   * 合法的参数值
   **/
  String[] paramValues();
 
  /**
   * 提示信息
   **/
  String message() default "参数不为指定值";
 
  Class<?>[] groups() default {};
 
  Class<? extends Payload>[] payload() default {};
}

@Target 定义注解的使用位置,用来说明该注解可以被声明在那些元素之前。

@Constraint 通过使用validatedBy来指定与注解关联的验证器

@Retention用来说明该注解类的生命周期。

验证器类

验证器类需要实现ConstraintValidator泛型接口

public class ParamConstraintValidated implements ConstraintValidator<Check, Object> {
  /**
   * 合法的参数值,从注解中获取
   * */
  private List<String> paramValues;
 
  @Override
  public void initialize(Check constraintAnnotation) {
    //初始化时获取注解上的值
    paramValues = Arrays.asList(constraintAnnotation.paramValues());
  }
 
  public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
    if (paramValues.contains(o)) {
      return true;
    }
 
    //不在指定的参数列表中
    return false;
  }
}

第一个泛型参数类型Check:注解,第二个泛型参数Object:校验字段类型。需要实现initialize和isValid方法,isValid方法为校验逻辑,initialize方法初始化工作

使用方式

定义一个实体类

@Data
public class User {
  /**
   * 姓名
   * */
  private String name;
 
  /**
   * 性别 man or women
   * */
  @Check(paramValues = {"man", "woman"})
  private String sex;
}

对sex字段加校验,其值必须为woman或者man

测试

@RestController("/api/test")
public class TestController {
  @PostMapping
  public Object test(@Validated @RequestBody User user) {
    return "hello world";
  }
}

注意需要在User对象上加上@Validated注解,这里也可以使用@Valid注解

方法、类注解

在开发过程中遇到过这样的需求,如只有有权限的用户的才能访问这个类中的方法或某个具体的方法、查找数据的时候先不从数据库查找,先从guava cache中查找,在从redis查找,最后查找mysql(多级缓存)。

这时候我们可以自定义注解去完成这个要求,第一个场景就是定义一个权限校验的注解,第二个场景就是定义spring-data-redis包下类似@Cacheable的注解。

权限注解

自定义注解

@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PermissionCheck {
  /**
   * 资源key
   * */
  String resourceKey();
}

该注解的作用范围为类或者方法上

拦截器类

public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
  /**
   * 处理器处理之前调用
   */
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
               Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod)handler;
    PermissionCheck permission = findPermissionCheck(handlerMethod);
 
    //如果没有添加权限注解则直接跳过允许访问
    if (permission == null) {
      return true;
    }
 
    //获取注解中的值
    String resourceKey = permission.resourceKey();
 
    //TODO 权限校验一般需要获取用户信息,通过查询数据库进行权限校验
    //TODO 这里只进行简单演示,如果resourceKey为testKey则校验通过,否则不通过
    if ("testKey".equals(resourceKey)) {
      return true;
    }
 
    return false;
  }
 
  /**
   * 根据handlerMethod返回注解信息
   *
   * @param handlerMethod 方法对象
   * @return PermissionCheck注解
   */
  private PermissionCheck findPermissionCheck(HandlerMethod handlerMethod) {
    //在方法上寻找注解
    PermissionCheck permission = handlerMethod.getMethodAnnotation(PermissionCheck.class);
    if (permission == null) {
      //在类上寻找注解
      permission = handlerMethod.getBeanType().getAnnotation(PermissionCheck.class);
    }
 
    return permission;
  }
}

权限校验的逻辑就是你有权限你就可以访问,没有就不允许访问,本质其实就是一个拦截器。我们首先需要拿到注解,然后获取注解上的字段进行校验,校验通过返回true,否则返回false

测试

 @GetMapping("/api/test")
 @PermissionCheck(resourceKey = "test")
 public Object testPermissionCheck() {
   return "hello world";
 }

该方法需要进行权限校验所以添加了PermissionCheck注解

缓存注解

自定义注解

@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomCache {
  /**
   * 缓存的key值
   * */
  String key();
}

注解可以用在方法或类上,但是缓存注解一般是使用在方法上的

切面

@Aspect
@Component
public class CustomCacheAspect {
  /**
   * 在方法执行之前对注解进行处理
   *
   * @param pjd
   * @param customCache 注解
   * @return 返回中的值
   * */
  @Around("@annotation(com.cqupt.annotation.CustomCache) && @annotation(customCache)")
  public Object dealProcess(ProceedingJoinPoint pjd, CustomCache customCache) {
    Object result = null;
 
    if (customCache.key() == null) {
      //TODO throw error
    }
 
    //TODO 业务场景会比这个复杂的多,会涉及参数的解析如key可能是#{id}这些,数据查询
    //TODO 这里做简单演示,如果key为testKey则返回hello world
    if ("testKey".equals(customCache.key())) {
      return "hello word";
    }
 
    //执行目标方法
    try {
      result = pjd.proceed();
    } catch (Throwable throwable) {
      throwable.printStackTrace();
    }
 
    return result;
  }
}

因为缓存注解需要在方法执行之前有返回值,所以没有通过拦截器处理这个注解,而是通过使用切面在执行方法之前对注解进行处理。如果注解没有返回值,将会返回方法中的值

测试

@GetMapping("/api/cache")
@CustomCache(key = "test")
public Object testCustomCache() {
  return "don't hit cache";
}

以上是“Spring自定义注解的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Spring Boot Admin的示例分析
  2. Spring Boot之AOP配自定义注解的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring

上一篇:Java如何实例化一个抽象类对象

下一篇:如何解决某些HTML字符打不出来的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》