SpringBoot攔截器中獲取註解、攔截器中注入Service

邢帅杰發表於2024-07-04
攔截器中獲取註解 來源:https://blog.csdn.net/wangmx1993328/article/details/81030268/
public class JWTInterceptor implements HandlerInterceptor {
    private SysSettingService sysSettingService;
    //建構函式傳入Service
    public JWTInterceptor(SysSettingService _sysSettingService) {
        sysSettingService = _sysSettingService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            //方法處理器, 請求的目標方法。RequirePermissions是自定義註解。
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //1: 獲取目標方法上的指定註解,不存在時,返回 Null
            RequirePermissions methodPermissions = handlerMethod.getMethodAnnotation(RequirePermissions.class);
            //2: 獲取目標方法所在類上的指定主鍵,不存在時,返回 Null
            RequirePermissions classPermissions = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequirePermissions.class);
            if (methodPermissions != null) {
                //獲取註解中的資料
                String[] permissions = methodPermissions.values();
            }
        }
} }

相關文章