springboot 中如何使用 swagger
Swagger是一个用于设计、构建、记录和使用RESTful Web服务的开源工具。在Spring Boot应用程序中,可以使用Swagger来自动生成API文档。
下面是在Spring Boot中使用Swagger的步骤:
在Maven或Gradle中添加Swagger相关的依赖。
在Spring Boot应用程序上添加Swagger注释。
设置Swagger的一些属性,如API文档的标题、版本、描述等。
配置SwaggerUI,以便用户可以访问API文档。
以下是一个使用Swagger生成API文档的示例:
- 添加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>
- 在Spring Boot应用程序上添加Swagger注释
在控制器的方法上添加注释,例如:
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/api/v1")
@Api(value = "用户管理", tags = "用户管理")
public class UserController {
@ApiOperation(value = "获取所有用户", notes = "获取所有用户的信息")
@GetMapping("/users")
public List<User> getAllUsers() {
// ...
}
@ApiOperation(value = "添加新用户", notes = "根据User对象创建新用户")
@PostMapping("/users")
public String addUser(@RequestBody User user) {
// ...
}
}
- 设置Swagger属性
配置Swagger属性,例如:
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户管理API文档")
.description("用户管理API接口文档")
.version("1.0.0")
.build();
}
}
- 配置SwaggerUI
配置SwaggerUI,例如:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class SwaggerUIConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/swagger-ui.html", "/swagger-ui/index.html");
}
}
完整的示例代码可以在Spring Boot官方文档中找到。
本作品采用《CC 协议》,转载必须注明作者和本文链接