SpringBoot使用Swagger2构建API文档

2019-11-05 16:03:02来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

SpringBoot使用Swagger2构建API文档

1、Swagger2介绍

  Swagger2这套自动化文档工具来生成文档,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。

2、SpringBoot开启Swagger2支持

  1、导入依赖

 

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

 

  2、设置配置类

package com.offcn.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public ApiInfo apiInfo(){
        return new ApiInfoBuilder().title("Spring Boot中使用Swagger2构建RESTful APIs").description("u就业")
                .termsOfServiceUrl("http://www.ujiuye.com/").contact("Sunny").version("0.0.1").build();
    }

    @Bean
    public Docket docket(){
        return  new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.offcn.demo.Controller"))
                .paths(PathSelectors.any()).build();
    }
}

  3、在controller层中的代码添加文档注释

通过@ApiOperation注解来给API增加说明 通过@ApiImplicitParams@ApiImplicitParam注解来给参数增加说明

@GetMapping("/getMap")
@ApiOperation(value = "获得数据",notes = "获得数据")
@ApiImplicitParam(name = "id" ,value = "用户id",required = true,dataType = "Integer")//required是否是必填属性
public Map getMap(Integer id){
     Map<String,String> map=new HashMap<>();
     map.put("name","xzy");
    return map;
}
@RequestMapping("/test/{id}")
@ApiOperation(value = "输出汽车的id和name",notes = "输出汽车的id和name")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "汽车id",dataType = "Integer",required = true),
@ApiImplicitParam(name = "name",value = "汽车牌子",dataType = "String",required = true)
})
public Car getCar(@PathVariable("id") Integer id, @RequestParam("name") String name){
Car c = new Car(id, name, 100000, new Date());
return c;
}

   4、查看生成的文档

  http://localhost:8080/swagger-ui.html

 

 


原文链接:https://www.cnblogs.com/xueziyeya/p/11801508.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:@Configuration

下一篇:SpringBoot依赖