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 定義註解的使用位置,用來說明該註解可以被聲明在那些元素之前。

ElementType.TYPE:說明該註解只能被聲明在一個類前。 ElementType.FIELD:說明該註解只能被聲明在一個類的字段前。 ElementType.METHOD:說明該註解只能被聲明在一個類的方法前。 ElementType.PARAMETER:說明該註解只能被聲明在一個方法參數前。 ElementType.CONSTRUCTOR:說明該註解只能聲明在一個類的構造方法前。 ElementType.LOCAL_VARIABLE:說明該註解只能聲明在一個局部變量前。 ElementType.ANNOTATION_TYPE:說明該註解只能聲明在一個註解類型前。 ElementType.PACKAGE:說明該註解只能聲明在一個包名前

  • @Constraint 通過使用validatedBy來指定與註解關聯的驗證器
  • @Retention用來說明該註解類的生命週期。

RetentionPolicy.SOURCE: 註解只保留在源文件中 RetentionPolicy.CLASS : 註解保留在class文件中,在加載到JVM虛擬機時丟棄
RetentionPolicy.RUNTIME: 註解保留在程序運行期間,此時可以通過反射獲得定義在某個類上的所有註解。

驗證器類

驗證器類需要實現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:校驗字段類型。需要實現initializeisValid方法,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";
}
複製代碼

小結

本篇文章主要介紹了開發過程中遇到自定義註解的場景以及自定義註解實現。如有紕漏,歡迎指正。
附:完整項目地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章