【Spring Swagger】5分钟上手swagger

1 简介

当我们在创建REST API时,需要有清晰的API说明文档,用于提供开发人员阅读和使用API。然而,在开发过程中每次更新API,需要同步更新API文档,这无疑是加重了开发工作量。

Swagger是一个用于快速构建API文档的工具,可以自己从代码中生成API说明文档。

下面将一步步描述如何向spring REST web service项目中引入swagger。

2 新建Spring Boot 工程

参考
Build a REST API with Spring 4 and Java Config article
Building a RESTful Web Service

spring boot 2.0.2

3 向Maven的配置pom.xml中添加依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
    <scope>compile</scope>
</dependency>

4 新建一个配置文件

SwaggerConfig.java

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

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

对于本应用,我们创建了一个Docket bean, 一个springfox Docket 实例提供原始的API配置,包含默认的配置和方法。
在这个配置文件中,@EnableSwagger2 注解用于开启该类的Swagger支持。select() 方法在Docket bean的实例中返回ApiSelectorBuilder ,它提供了api() 方法和 path() 方法来过滤controller和谓语的方法。

5 访问api-doc

原始以json描述的 API
http://localhost:8080/v2/api-docs
api-docs JSON

6 访问UI界面

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

swagger UI

参考:
https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值