Swagger2太多相同的注释

时间:2017-12-04 06:11:17

标签: java spring-boot swagger

我将swagger2集成到springboot项目,因为我的所有端点授权都是OAuth2,所以我需要为每个方法添加Authorization标头,如下面的代码:

@ApiImplicitParams({     
    @ApiImplicitParam(paramType="header",name="Authorization",dataType="String",required=true, value="Bearer {access-token}")
})

这些相同的注释太多了,我可以用一些方法来重构它们吗?

Swagger2 Docket代码:

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build();
}

1 个答案:

答案 0 :(得分:2)

我花了几天时间找出解决方案。在这里,我给你access_token的文件夹配置。配置全局参数,可以说包含每个端点的公共参数(access_token)。因此,您不需要在每个端点都包含@ApiImplicitParams。下面给出了可能的文档配置(稍后您可以更改自己的 api信息)。

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.resource"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(commonParameters())
            .apiInfo(apiInfo())
            .ignoredParameterTypes(TokenInfo.class, HttpServletRequest.class, HttpServletResponse.class)
            .securityContexts(Lists.newArrayList(securityContext()))
            .securitySchemes(Lists.newArrayList(apiKey()));
}


private List<Parameter> commonParameters() {
    List<Parameter> parameters = new ArrayList<Parameter>();
    parameters.add(new ParameterBuilder()
            .name("access_token")
            .description("token for authorization")
            .modelRef(new ModelRef("string"))
            .parameterType("query")
            .required(true)
            .build());

    return parameters;
}

private ApiInfo apiInfo() {
    ApiInfo apiInfo = new ApiInfo(
            "My REST API",
            "Some custom description of API.",
            "API TOS",
            "Terms of service",
            "myeaddress@company.com",
            "License of API",
            "API license URL");
    return apiInfo;
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("AUTHORIZATION", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("AUTHORIZATION", "access_token", "header");
}

只需粘贴代码并尝试swagger-ui并告诉我状态。