简体   繁体   English

如何为swagger api添加一个通用参数

[英]How add a common parameter for swagger api

I my project there are lots of controllers with such annotation 我的项目中有很多带有这种注释的控制器

    @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
    ){
           // ..
    }

almost every method accept common parameter like access_token . 几乎每个方法都接受像access_token这样的公共参数。 It will bad solution if we add description about it to all methods. 如果我们将描述添加到所有方法,那将是不好的解决方案。 Maybe there is other solution? 也许有其他解决方案?

I found that i can define json file with such configuration like here https://github.com/OAI/OpenAPI-Specification/blob/master/fixtures/v2.0/json/resources/reusableParameters.json , but as i understood i can use either json or annotation. 我发现我可以使用这样的配置来定义json文件,例如https://github.com/OAI/OpenAPI-Specification/blob/master/fixtures/v2.0/json/resources/reusableParameters.json ,但是据我了解我可以使用json或注释。 Or maybe i can combine them somehow? 或者也许我可以以某种方式结合它们?

If someone will be search for something like this. 如果有人会搜索这样的东西。 I found next solution. 我发现下一个解决方案 In project we configure swagger like this 在项目中,我们配置像这样的招摇

@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;
    }
}

You should call globalOperationParameters method and pass there list of global paramets(i create it in commonParameters method). 你应该调用globalOperationParameters方法并传递全局参数列表(我在commonParameters方法中创建它)。

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

Thats all. 就这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM