Swagger開發(含文件上傳)和文檔導出

Swagger好處啥的略過,因爲需要用,所以就用了。

廢話不多說,直接上步驟

Swagger開發(基於maven工程,swagger2包)

關於swagger的相關注解,可以參見 https://blog.csdn.net/xiaojin21cen/article/details/78654652

1、依賴添加

            <!-- swagger -->

                            <dependency>

                                  <groupId>io.springfox</groupId>

                                  <artifactId>springfox-swagger2</artifactId>

                                  <version>2.7.0</version>

                              </dependency>

                           

                            <!-- swagger-ui爲項目提供api展示及測試的界面 -->

                              <dependency>

                                  <groupId>io.springfox</groupId>

                                  <artifactId>springfox-swagger-ui</artifactId>

                                  <version>2.7.0</version>

                              </dependency>

2、添加配置類,新建一個類SwaggerConfig,代碼如下

 

@Configuration //聲明該類爲配置類

@EnableSwagger2 //聲明啓動Swagger2

@EnableWebMvc //聲明啓動mvc

@ComponentScan("com.XXXX.service")

public class SwaggerConfig{

    

              @Bean

              public Docket apiDocket(){

                      

                       //添加header參數

                     ParameterBuilder username = new ParameterBuilder();

                     List<Parameter> pars = new ArrayList<>();

                     username.name("username")

                                    .description("用戶名")

                             .modelRef(new ModelRef("string"))

                             .parameterType("header")

                             .required(false).build(); //header中的username

                     pars.add(username.build());   

                    

                     ParameterBuilder password = new ParameterBuilder();

                     password.name("password")

                                    .description("密碼")

                             .modelRef(new ModelRef("string"))

                             .parameterType("header")

                             .required(false).build(); //header中的password

                     pars.add(password.build());  

                      

                       return new Docket(DocumentationType.SWAGGER_2)

                       .apiInfo(apiInfo())

                       .select()

/*                   .apis(RequestHandlerSelectors.basePackage("com.XXX.service "))*/

                       .paths(PathSelectors.any())

                       .build()

                       .globalOperationParameters(pars);

              }

 

              private ApiInfo apiInfo() {

             return new ApiInfoBuilder()

                     .title("測試接口")//文檔說明

                     .version("1.0")//文檔版本說明

                     .build();

         }

             

}

3、添加實體類

@ApiModel(value="產品信息",description="產品信息")

public class Product{

 

    private static final long serialVersionUID = 1L;

 

    /** ID */

    private Long id;

 

    /** 產品名稱 */

    @ApiModelProperty(value = "產品名稱", name="name", required = true)

    private String name;

 

    /** 產品型號 */

    @ApiModelProperty(value = "產品型號", name="productClass", required = true)

    private String productClass;

 

    /** 產品ID */

    @ApiModelProperty(value = "產品ID", name="productId", required = true)

    private String productId;

 

    public Long getId() {

        return id;

    }

 

    public void setId(Long id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public String getProductClass() {

        return productClass;

    }

 

    public void setProductClass(String productClass) {

        this.productClass = productClass;

    }

 

    public String getProductId() {

        return productId;

    }

 

    public void setProductId(String productId) {

        this.productId = productId;

    }

 

    @Override

    public String toString() {

        return "Product [id=" + id + ", name=" + name + ", productClass="

                + productClass + ", productId=" + productId + "]";

    }

 

4、添加接口

@RestController

@Api(description="測試1controller")

@RequestMapping(value = {"/product/"})

public class ProductController extends BaseController{

 

   

    @ApiOperation(value = "here is @ApiOperation value",tags = "測試接口2(here is @Api tags)", notes = "here is @ApiOperation notes")

    @RequestMapping(value = "helloSwagger", method = RequestMethod.POST)

    @ApiResponses({ @ApiResponse(code = 400, message = "error") })

    public @ResponseBody String helloSwagger(

                       Product product){

        return product.getName()+":"+product.getProductClass();

    }

}

 

 

Ok,到這裏,代碼完成,項目跑起來

然後打開瀏覽器,輸入http://localhost:8080/你的項目名/swagger-ui.html#/

就可以看到在線生成的接口文檔。如果到這沒問題,那麼請在瀏覽器中輸入

http://localhost:8080/你的項目名/v2/api-docs如果網頁返回json格式的字符串,那下一步導出纔有可能。

 

Swagger文檔導出

這兩提供兩種,一種是基於html和PDF格式的文件導出,另一種是基於doc格式的文件導出

1、基於基於html和PDF格式的文件導出

可以參見這個https://blog.csdn.net/java_collect/article/details/84480588 ,裏面介紹的很詳細,推薦使用方法2

2、基於doc格式導出

可以參見https://bbs.huaweicloud.com/blogs/120234,這裏介紹得很詳細

 

開發和文檔一站式搞定。

關鍵點:

swagger對於文件上傳的支持感覺並不是太友好,如果是單文件上傳,那基本是沒問題的,如果是多文件上傳,那問題就不少。

單文件上傳:

    @ApiOperation(value = "here is @ApiOperation value",tags = "測試接口2(here is @Api tags)", notes = "here is @ApiOperation notes")

    @RequestMapping(value = "helloSwagger", method = RequestMethod.POST,headers=”Content-Type=multipart/form-data”)

    @ApiResponses({ @ApiResponse(code = 400, message = "error") })

    @ApiImplicitParams({

                   @ApiImplicitParam(name = "file",value = "文件,",paramType = "formData",dataType = "file")

         })

 

    public @ResponseBody String helloSwagger(

                       Product product,

                       @RequestParam(value = "file")MultipartFile file){

             …………

        return product.getName()+":"+product.getProductClass();

    }

測試的話,單文件可以直接在http://localhost:8080/你的項目名/swagger-ui.html#/上面測試

多文件上傳:

    @ApiOperation(value = "here is @ApiOperation value",tags = "測試接口2(here is @Api tags)", notes = "here is @ApiOperation notes")

    @RequestMapping(value = "helloSwagger", method = RequestMethod.POST,headers=”Content-Type=multipart/form-data”)

    @ApiResponses({ @ApiResponse(code = 400, message = "error") })

    @ApiImplicitParams({

                   @ApiImplicitParam(name = "file",value = "文件,",paramType = "formData",allowMultiple=true,dataType = "file")

         })

 

    public @ResponseBody String helloSwagger(

                       Product product,

                       @RequestParam(value = "file")MultipartFile[] file){

             …………

        return product.getName()+":"+product.getProductClass();

    }

 

測試的話,多文件只能在postman上面測試,swagger自帶的在線測試是不支持多文件測試的。

用postman測試就ok了?不不不,這裏還有坑,postman測試時,如果是有文件的情況下,file參數格式要選擇file,如果要是文件爲空的情況下,file參數格式要選擇text,否則測試會報錯

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章