关注微信公众号(瓠悠笑软件部落),一起学习,一起摸鱼

- spring boot 开发 restful 接口
- 用swagger2 生成API文档,可以在浏览器里面查看
Swagger UI 官网
OpenAPI 规范
swagger2 pom.xml 依赖
spring boot 工程用的maven,需要在pom.xml文件中添加:
. . .
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
<scope>compile</scope>
</dependency>
. . .
配置文件
新建 SwaggerConfig 类, 继承 WebMvcConfigurationSupport
package com.huyouxiao.wait.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("com.huyouxiao.wait.controller"))
.paths(regex("/wait.*"))
.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/");
}
}
- 在此配置类中, @ EnableSwagger2批注在类中启用Swagger支持。
- 在Docket bean实例上调用的 select ()方法 返回一个 ApiSelectorBuilder,它提供 apis ()和 paths ()方法来过滤使用String谓词记录的控制器和方法。
- paths(regex("/wait.*")) 表示 请求URI以wait的接口, 会生成文档,其他的忽略。
访问地址
访问地址:
定制Swagger
在SwaggerController类里面添加metaData方法
private ApiInfo metaData() {
return new ApiInfoBuilder()
.title("Spring Boot REST API")
.description("\"Spring Boot REST API for Online Store\"")
.version("1.0.0")
.license("Apache License Version 2.0")
.licenseUrl("https://www.apache.org/licenses/LICENSE-2.0\"")
.contact(new Contact("John Thompson", "https://springframework.guru/about/", "john@springfrmework.guru"))
.build();
}
本文介绍了如何在Spring Boot项目中使用Swagger2生成RESTful API文档,包括添加pom.xml依赖,配置SwaggerConfig,设置请求URI过滤,并提供了访问Swagger UI的地址,以及如何定制Swagger信息。
1424

被折叠的 条评论
为什么被折叠?



