如何为swagger API添加通用参数

Ole*_*iak 4 json restful-architecture swagger-ui

我的项目中有很多带有此类注释的控制器

    @ApiOperation(value = "description")
    @RequestMapping(value = "/{param1}", method = RequestMethod.POST)
    public @ResponseBody Response<Map<String, Object>> someMethod(
       @ApiParam(name = "param1", value = "about param1", required = true)
       @PathVariable("param1") int param1,

       @ApiParam(name = "param2", value = "about param2", required = false, defaultValue = "default)
       @RequestParam(value = "param2", defaultValue = "default") String param2
    ){
           // ..
    }
Run Code Online (Sandbox Code Playgroud)

几乎每种方法都接受通用参数,例如access_token。如果将描述添加到所有方法中,将是不好的解决方案。也许还有其他解决方案?

我发现我可以json使用这样的配置来定义文件,例如:https://github.com/OAI/OpenAPI-Specification/blob/master/fixtures/v2.0/json/resources/reusableParameters.json,但是据我所知我可以使用json或注释。或者,也许我可以以某种方式将它们结合起来?

Ole*_*iak 5

如果有人会搜索这样的东西。我找到了下一个解决方案。在项目中,我们像这样配置招摇

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(commonParameters())
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(/* params here */);
        return apiInfo;
    }


    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(false)
                .build());

        return parameters;
    }
}
Run Code Online (Sandbox Code Playgroud)

您应该调用globalOperationParametersmethod并传递全局参数列表(我在commonParametersmethod中创建它)。

我在这里找到的解决方案http://springfox.github.io/springfox/docs/current/

就这样。