Spring Boot:自定义注解--annotation

Dear 丶 2024-02-24 06:25 77阅读 0赞

目录

  • 自定义注解的定义和作用范围
  • 如何创建自定义注解
    • 创建注解接口
  • 如何使用自定义注解进行数据验证
    • 创建注解处理器
    • 控制器中使用注解
  • 如何为字段添加注解

自定义注解的定义和作用范围

  • 自定义注解可以作用在类、方法、属性、参数、异常、字段或其他注解上。

如何创建自定义注解

创建注解接口

在这里插入图片描述

  1. package hanshuhuan.test.anonotion;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * 实体检验自定义注解类,根据我们自定义的注解去检查实体各个字段是否在规定的值内
  8. * @author shuhu
  9. *
  10. */
  11. @Target(ElementType.FIELD)
  12. @Retention(RetentionPolicy.RUNTIME)
  13. public @interface ValidateEntity {
  14. public boolean required() default false;//是否检验null
  15. public boolean requiredLeng() default false;//是否检验长度
  16. public boolean requiredMaxValue() default false;//是否检验最大值
  17. public boolean requiredMinValue() default false;//是否检验最小值
  18. public int maxLength() default -1;//最大长度
  19. public int minLength() default -1;//最小长度
  20. public long maxValue() default -1;//最大值
  21. public long minValue() default -1;//最小值
  22. public String errorRequiredMsg() default "";//值为null时的错误提示信息
  23. public String errorMinLengthMsg() default "";//最小长度不满足时的提示信息
  24. public String errorMaxLengthMsg() default "";//最大长度不满足时的提示信息
  25. public String errorMinValueMsg() default "";//最小值不满足时的提示信息
  26. public String errorMaxValueMsg() default "";//最大值不满足时的提示信息
  27. }

如何使用自定义注解进行数据验证

创建注解处理器

  1. package hanshuhuan.test.util;
  2. import java.lang.reflect.Field;
  3. import hanshuhuan.test.anonotion.ValidateEntity;
  4. import hanshuhuan.test.bean.CodeMsg;
  5. /**
  6. * 验证实体工具类
  7. * @author shuhu
  8. *
  9. */
  10. public class ValidateEntityUtil {
  11. public static CodeMsg validate(Object object){
  12. Field[] declaredFields = object.getClass().getDeclaredFields();
  13. for(Field field : declaredFields){
  14. ValidateEntity annotation = field.getAnnotation(ValidateEntity.class);
  15. if(annotation != null){
  16. if(annotation.required()){
  17. //表示该字段是必填字段
  18. field.setAccessible(true);
  19. try {
  20. Object o = field.get(object);
  21. //首先判断是否为空
  22. if(o == null){
  23. CodeMsg codeMsg = CodeMsg.VALIDATE_ENTITY_ERROR;
  24. codeMsg.setMsg(annotation.errorRequiredMsg());
  25. return codeMsg;
  26. }
  27. //到这,说明该变量的值不是null
  28. //首先判断是不是String类型
  29. if(o instanceof String){
  30. //若是字符串类型,则检查其长度
  31. if(annotation.requiredLeng()){
  32. if(o.toString().length() < annotation.minLength()){
  33. CodeMsg codeMsg = CodeMsg.VALIDATE_ENTITY_ERROR;
  34. codeMsg.setMsg(annotation.errorMinLengthMsg());
  35. return codeMsg;
  36. }
  37. if(o.toString().length() > annotation.maxLength()){
  38. CodeMsg codeMsg = CodeMsg.VALIDATE_ENTITY_ERROR;
  39. codeMsg.setMsg(annotation.errorMaxLengthMsg());
  40. return codeMsg;
  41. }
  42. }
  43. }
  44. //其次来判断是否为数字
  45. if(isNumberObject(o)){
  46. //判断是否规定检查最小值
  47. if(annotation.requiredMinValue()){
  48. if(Double.valueOf(o.toString()) < annotation.minValue()){
  49. CodeMsg codeMsg = CodeMsg.VALIDATE_ENTITY_ERROR;
  50. codeMsg.setMsg(annotation.errorMinValueMsg());
  51. return codeMsg;
  52. }
  53. }
  54. //判断是否规定检查最大值
  55. if(annotation.requiredMaxValue()){
  56. if(Double.valueOf(o.toString()) > annotation.maxValue()){
  57. CodeMsg codeMsg = CodeMsg.VALIDATE_ENTITY_ERROR;
  58. codeMsg.setMsg(annotation.errorMaxValueMsg());
  59. return codeMsg;
  60. }
  61. }
  62. }
  63. } catch (IllegalArgumentException e) {
  64. // TODO Auto-generated catch block
  65. e.printStackTrace();
  66. } catch (IllegalAccessException e) {
  67. // TODO Auto-generated catch block
  68. e.printStackTrace();
  69. }
  70. }
  71. }
  72. }
  73. return CodeMsg.SUCCESS;
  74. }
  75. /**
  76. * 检查对象是否是数字类型
  77. * @param object
  78. * @return
  79. */
  80. public static boolean isNumberObject(Object object){
  81. if(object instanceof Integer)return true;
  82. if(object instanceof Long)return true;
  83. if(object instanceof Float)return true;
  84. if(object instanceof Double)return true;
  85. return false;
  86. }
  87. }

控制器中使用注解

  1. @RequestMapping(value="/login",method=RequestMethod.POST)
  2. @ResponseBody
  3. public Result<Boolean> login(User user,String cpacha){
  4. if(user == null){
  5. return Result.error(CodeMsg.DATA_ERROR);
  6. }
  7. //用统一验证实体方法验证是否合法
  8. CodeMsg validate = ValidateEntityUtil.validate(user);
  9. if(validate.getCode() != CodeMsg.SUCCESS.getCode()){
  10. return Result.error(validate);
  11. }
  12. //表示实体信息合法,开始验证验证码是否为空
  13. if(StringUtils.isEmpty(cpacha)){
  14. return Result.error(CodeMsg.CPACHA_EMPTY);
  15. }
  16. log.info("ok"+user);
  17. return Result.success(true);
  18. }

如何为字段添加注解

  • 自定义注解的定义是通过@注解名的方式实现的。

    @ValidateEntity(required=true,requiredLeng=true,minLength=4,maxLength=18,errorRequiredMsg=”用户名不能为空!”,errorMinLengthMsg=”用户名长度需大于4!”,errorMaxLengthMsg=”用户名长度不能大于18!”)
    @Column(name=”username”,nullable=false,length=18)
    private String username;//用户名

    @ValidateEntity(required=true,requiredLeng=true,minLength=4,maxLength=32,errorRequiredMsg=”密码不能为空!”,errorMinLengthMsg=”密码长度需大于4!”,errorMaxLengthMsg=”密码长度不能大于32!”)
    @Column(name=”password”,nullable=false,length=32)
    private String password;//密码

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读