一、Swagger是什麼?
Swagger是一個面向RESTful API的開源軟體框架。它提供了一組工具,可以幫助您描述、生成、消費API。通過使用Swagger,您可以更好地了解API的工作方式以及如何使用它。
Spring Boot集成Swagger,可以讓我們在開發API文檔時,少寫很多樣板代碼,Swagger生成器會根據註解自動生成API文檔,並且生成的API文檔非常詳細,展示了API的參數、請求方式、響應格式等等。
二、快速上手Swagger
1、首先,在pom.xml中引入Swagger的依賴。
<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、創建Swagger2配置類,配置Swagger基本信息
package com.example.swaggerdemo.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 {
@Bean
public Docket createApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerDemo API")
.description("SwaggerDemo後台API介面文檔")
.termsOfServiceUrl("http://127.0.0.1:8080/")
.version("1.0")
.build();
}
}
3、在Controller層的方法上使用Swagger註解,用於API的說明、請求參數的說明等。
@Api(tags = "用戶管理")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@ApiOperation(value = "獲取用戶列表")
@GetMapping("/")
public List<User> getUserList() {
return userRepository.findAll();
}
@ApiOperation(value = "新增用戶")
@PostMapping("/")
public User addUser(@ApiParam(value = "用戶對象", required = true) @RequestBody User user) {
return userRepository.save(user);
}
@ApiOperation(value = "根據ID查詢用戶")
@GetMapping("/{id}")
public User getUserById(@ApiParam(value = "用戶ID", required = true) @PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
@ApiOperation(value = "根據ID更新用戶信息")
@PutMapping("/{id}")
public User updateUserById(@ApiParam(value = "用戶ID", required = true) @PathVariable Long id,
@ApiParam(value = "用戶對象", required = true) @RequestBody User user) {
user.setId(id);
return userRepository.save(user);
}
@ApiOperation(value = "根據ID刪除用戶")
@DeleteMapping("/{id}")
public void deleteUserById(@ApiParam(value = "用戶ID", required = true) @PathVariable Long id) {
userRepository.deleteById(id);
}
}
三、Swagger的常用註解
Swagger常用註解有@Api、@ApiOperation、@ApiParam、@ApiModel、@ApiModelProperty這些註解。
1、@Api:標記一個Controller類為Swagger資源。
2、@ApiOperation:標記Controller方法為Swagger操作。
3、@ApiParam:標記方法參數的名稱和描述。
4、@ApiModel和@ApiModelProperty:用於Swagger Model類的Javadoc。其中,@ApiModel描述模型的名稱和說明,@ApiModelProperty描述模型屬性的名稱、描述信息、是否必須等。
四、Swagger的高級用法
1、全局配置
通過SwaggerConfig的apiInfo()方法,可以設置所有Controller的通用信息。
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerDemo API")
.description("SwaggerDemo後台API介面文檔")
.termsOfServiceUrl("http://127.0.0.1:8080/")
.version("1.0")
.contact(new Contact("SwaggerDemo", "", "xxx@qq.com")) //設置API創建人信息
.license("Apache License 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
2、局部配置
可以在方法級別上對Swagger進行局部配置,例如針對某個方法不展示。
@ApiOperation(value = "獲取用戶列表")
@ApiResponses(value = {
@ApiResponse(code = 401, message = "未授權"),
@ApiResponse(code = 403, message = "禁止訪問")
})
@GetMapping("/")
public List<User> getUserList() {
return userRepository.findAll();
}
3、返回新的數據類型
在Swagger中,我們可以在ResponseBoby註解中使用ResponseContainer註解定義響應數據的格式,常見的格式有List、Set、Map、具體類等。
@ApiOperation(value = "獲取用戶列表")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "獲取成功", response = User.class, responseContainer = "List")
})
@GetMapping("/")
public List<User> getUserList() {
return userRepository.findAll();
}
五、Swagger-UI的使用
Swagger-UI是Swagger的前端框架,可以通過Swagger生成的json或yaml文件來展示API文檔。
1、引入Swagger-UI的依賴。
<dependency>
<groupId>org.webjars</groupId>
<artifactId>swagger-ui</artifactId>
<version>2.1.4</version>
</dependency>
2、在Spring Boot的配置文件中配置Swagger-UI的訪問路徑。
spring.mvc.static-path-pattern=/swagger/** spring.resources.static-locations=classpath:/META-INF/resources/webjars/
3、啟用Swagger-UI
在SwaggerConfig類中添加以下代碼:
@Bean
public Docket createApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller"))
.paths(PathSelectors.any())
.build();
}
@Bean
public UiConfiguration getUiConfig() {
return UiConfigurationBuilder.builder()
.docExpansion(SwaggerUiConfiguration.DocExpansion.LIST)
.build();
}
4、訪問Swagger-UI
啟動Spring應用,訪問http://localhost:8080/swagger-ui.html,即可看到Swagger-UI的展示界面。
六、總結
本文詳細闡述了Swagger的概念、快速上手、常用註解、高級用法以及Swagger-UI的使用,是學習Swagger的不錯教程。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/309594.html
微信掃一掃
支付寶掃一掃