Swagger是一個接口文檔生成工具,在前后端分離的開發中經常會用到,下面就來介紹下Swagger的使用:
引入依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
配置Swagger
新建一個SwaggerConfig文件,輸入
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文檔")
.description("這里是描述信息")
.contact(new Contact("JoeyHua", "https://home.cnblogs.com/u/joeyhua", "1601939052@qq.com"))
.version("1.0")
.build();
}
}
使用注解
在項目的Application文件中添加@EnableOpenApi
注解
@EnableOpenApi
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication .class, args);
}
}
在Controller文件中添加@Api
和@ApiOperation
注解
@Api(tags = "Demo")
@RestController
@RequestMapping("/demo")
public class DemoController {
@ApiOperation("sayHello")
@GetMapping("/sayHello")
public String sayHello() {
return "Hello";
}
}
運行程序,瀏覽器訪問http://ip:port/swagger-ui/index.html即可看到效果
美化Swagger文檔界面
原生的Swagger文檔界面有些簡陋,可以使用knife4j美化界面,只需引入依賴即可
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
這里要注意,knife4j的頁面地址和原生地址不同,為http://ip:port/doc.html#/home,訪問即可看到效果
小福利
最近寫了一個前端Service文件自動生成工具,輸入Swagger文檔的地址即可自動生成Service文件,支持主流的HTTP客戶端庫,如axios和umi-request,支持生成TS文件,感興趣的同學可以看一下。
github地址:https://github.com/huajiayi/openapi-tool
相關博客:https://www.cnblogs.com/joeyhua/p/15357143.html