1、添加依赖:两个(一个核心、一个ui)
2、创建配置类
3、访问:http://localhost:8080/swagger-ui.html
- 添加Swagger依赖:在您的Spring Boot项目的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>
- 创建Swagger配置类:在您的Spring Boot项目中创建一个Swagger配置类,例如
SwaggerConfig.java
,并添加@Configuration
和@EnableSwagger2
注解。
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 api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("描述您的API信息")
.version("1.0")
.build();
}
}
- 创建API控制器:创建您的API控制器,例如
UserController.java
,并添加相关的注解。
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List<User> getAllUsers() {
// 返回用户数据
}
@PostMapping
public void createUser(@RequestBody User user) {
// 创建用户
}
@PutMapping("/{id}")
public void updateUser(@PathVariable Long id, @RequestBody User user) {
// 更新用户
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable Long id) {
// 删除用户
}
}
-
运行应用程序:启动您的Spring Boot应用程序。
-
查看Swagger文档:在浏览器中访问以下URL,即可查看生成的Swagger API文档:
http://localhost:8080/swagger-ui.html
在Swagger UI界面上,您将看到自动生成的API文档,包括可用的端点、请求参数、响应示例等信息。