Spring boot 整合 swagger2

       在服务端的开发过程中,后端开发人员往往会提供很多API接口出来供客户端的开发人员使用,经常会维护一份文档,注明每个接口的访问方式,需要的参数和返回的结果等基本信息。这种传统的API书写方式很费时间,而且容易造成因为接口文档更新不及时导致前后端开发人员的沟通成本的增加。利用swagger可以很方便、直观的将后台所定义接口展示给客户端开发人员,而且还给后台开发人员节省了很多时间成本。swagger这么方便好用,那我们现在就开始进行整合吧

1、引入swagger所需要的jar包

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.9</version>
</dependency>

2、自定义swagger的基本配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot Demo中使用Swagger2构建RESTful APIs")
                .version("1.0.0")
                .build();
    }
}

3、编写测试的controller

@RestController
public class ProductCategoryController {
    @Autowired
    private ProductCategoryService categoryService;

    @GetMapping("db/findByCategoryType/{type}")
    @ApiOperation(value = "查询类型", notes = "根据CategoryType来查询类型")
    public ResultVO getCategory(@PathVariable("type") Integer type) {
        return ResultVOUtil.success(categoryService.findByCategoryType(type));
    }
}

4、在 GitHub 上下载 SwaggerUI 项目(https://github.com/swagger-api/swagger-ui),将dist下所有内容拷贝到本地项目resource/static/swagger下面, 并修改 index.html

//url: "http://petstore.swagger.io/v2/swagger.json",
//url: "http://localhost:8086/demo/v2/api-docs",
url: location.protocol + '//' + location.host + "/demo/v2/api-docs",

5、然后访问http://localhost:8086/demo/swagger/index.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值