一、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/n/309594.html
微信扫一扫
支付宝扫一扫