类注解、方法注解

ⅰ亾dé卋堺 提交于 2019-12-05 04:54:00

定义注解类:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SignCheck {

    RequiredType required() default RequiredType.FORCE;
    
}

定义拦截器:

public class ApiSignInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        SignCheck signCheck = InterceptorUtils.getAnnotaion(handler, SignCheck.class);
        if (signCheck == null) {
            return true;
        } else {
            return signCheck(request, response);
        }
    }

    private boolean signCheck(HttpServletRequest request, HttpServletResponse response) {
        // 判断逻辑
        return false;
    }

}

工具类:

public class InterceptorUtils {

    private static Logger logger = getLogger(InterceptorUtils.class);

    private InterceptorUtils() {
    }

    // CHECKSTYLE:OFF
    public static <A extends Annotation> A getAnnotaion(Object handler, Class<A> annotationClass) {
        if (!(handler instanceof HandlerMethod)) {
            return null;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        A result;
        if ((result = findAnnotation(handlerMethod.getMethod(), annotationClass)) != null) {
            logger.trace("found [{}] annotation in method-level:{}",
                    annotationClass.getSimpleName(), handlerMethod.getMethod());
        } else {
            if ((result = findAnnotation(handlerMethod.getBeanType(), annotationClass)) != null) {
                logger.trace("found [{}] annotation in type-level:{}",
                        annotationClass.getSimpleName(), handlerMethod.getBeanType());
            }
        }
        return result;
    }

    public static String firstNotBlank(String... values) {
        return Arrays.stream(values).sequential().filter(StringUtils::isNotBlank).findFirst()
                .orElse(null);
    }

    @Nullable
    public static Map<String, String> errTipToMap(@Nullable String[] errTips) {
        // 是空或者不是偶数个,返回空
        if (ArrayUtils.isEmpty(errTips) || errTips.length % 2 != 0) {
            return null;
        }
        return IntStream.range(0, errTips.length / 2).boxed()
                .collect(toMap(i -> errTips[i * 2], i -> errTips[i * 2 + 1]));
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!