通过header控制接口版本

自定义指定接口版本注解

/**
 * @author wangningbo
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface APIVersion {
    String value();

    String headerKey() default "version";
}

继承RequestCondition实现自定义

/**
 * 自定义 RequestCondition
 *
 * @author wangningbo
 */
public class APIVersionCondition implements RequestCondition {
    
    @Getter
    private String apiVersion;
    @Getter
    private String headerKey;

    public APIVersionCondition(String apiVersion, String headerKey) {
        this.apiVersion = apiVersion;
        this.headerKey = headerKey;
    }

    @Override
    public APIVersionCondition combine(APIVersionCondition other) {
        return new APIVersionCondition(other.getApiVersion(), other.getHeaderKey());
    }

    @Override
    public APIVersionCondition getMatchingCondition(HttpServletRequest request) {
        String version = request.getHeader(headerKey);
        return apiVersion.equals(version) ? this : null;
    }

    @Override
    public int compareTo(APIVersionCondition other, HttpServletRequest request) {
        return 0;
    }
}

继承 RequestMappingHandlerMapping 实现自定义

/**
 * @author wangningbo
 */
public class AutoPrefixUrMapping extends RequestMappingHandlerMapping {
    @Override
    protected boolean isHandler(Class beanType) {
        return AnnotatedElementUtils.hasAnnotation(beanType, Controller.class);
    }

    @Override
    protected RequestCondition getCustomTypeCondition(Class handlerType) {
        APIVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, APIVersion.class);
        return createCondition(apiVersion);
    }

    @Override
    protected RequestCondition getCustomMethodCondition(Method method) {
        APIVersion apiVersion = AnnotationUtils.findAnnotation(method, APIVersion.class);
        return createCondition(apiVersion);
    }

    private RequestCondition createCondition(APIVersion apiVersion) {
        return apiVersion == null ? null : new APIVersionCondition(apiVersion.value(), apiVersion.headerKey());
    }
}

使用自定义注解控制版本

    @APIVersion("1.0")
    @ApiOperation(value = "单个查询", notes = "1.0版本")
    @GetMapping("/id/{id}")
    public CategoryVO getById(@PathVariable Long id) {
    }

    @APIVersion("2.0")
    @ApiOperation(value = "单个查询", notes = "2.0版本")
    @GetMapping("/id/{id}")
    public CategoryVO getById2(@PathVariable Long id) {
    }

你可能感兴趣的:(通过header控制接口版本)