💡简介
Swagger 是一个开源的框架,用于设计、构建、文档化和使用 RESTful 风格的 Web 服务。Spring Boot 是一个用于构建独立的、基于生产级别的 Spring 应用程序的框架。它可以集成 Swagger 来简化 RESTful API 的开发和文档生成。
通过集成 Swagger,你可以在 Spring Boot 应用程序中自动生成 API 文档,这些文档描述了你的 API 的各种端点、请求参数、响应等详细信息。Swagger 还提供了一个交互式 UI,让开发人员可以方便地浏览和测试 API。
💡实例
🌵版本依赖
JDK17
SpringBoot 2.5.4
swagger 3.0.0
knife4j-spring-boot-starter 3.0.2
🌵引入依赖
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-swagger</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入spring web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入swagger3 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!--Knife4j-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.example.SpringbootSwaggerSampleApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
🌵SwaggerConfig
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Response;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: (Swagger配置)
* @Date 2023/09/07
*/
@Configuration
@EnableOpenApi
@EnableKnife4j
public class SwaggerConfig {
/**
* swagger3的配置文件
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
//.globalRequestParameters(getGlobalRequestParameters())
.globalResponses(HttpMethod.GET, getGlobalResponseMessage())
.globalResponses(HttpMethod.POST, getGlobalResponseMessage())
.globalResponses(HttpMethod.DELETE, getGlobalResponseMessage())
.globalResponses(HttpMethod.PUT, getGlobalResponseMessage());
}
/**
* 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
*/
private ApiInfo apiInfo() {
// 获取工程名称
String projectName = System.getProperty("user.dir");
return new ApiInfoBuilder()
.title(projectName.substring(projectName.lastIndexOf("\") + 1) + " API接口文档")
.contact(new Contact("coderJim", "https://www.example.com", "coderJim@163.com"))
.version("1.0")
.description("API文档")
.build();
}
/**
* 生成通用响应信息
*
* @return
*/
private List<Response> getGlobalResponseMessage() {
List<Response> responseList = new ArrayList<>();
responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
return responseList;
}
}
🌵User
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
/**
* @Description: (用一句话描述该文件做什么)
* @date 2023/09/07
*/
@Data
@ToString
@ApiModel(value = "用户实体类", description = "用户信息描述类")
public class User {
@ApiModelProperty(value = "用户id")
private Integer id;
@ApiModelProperty(value = "用户名")
private String username;
@ApiModelProperty(value = "用户密码")
private String password;
}
🌵UserController
import com.example.entity.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
/**
*
* @Package com.example.controller
* @Description: (用一句话描述该文件做什么)
* @date 2023/09/07
*/
@RestController
@Api(tags = "用户数据接口") // @Api 注解标注在类上用来描述整个 Controller 信息。
public class UserController {
/**
* @ApiOperation 注解标注在方法上,用来描述一个方法的基本信息。
*/
@ApiOperation(value = "修改用户", notes = "传入用户信息进行更新修改")
@PutMapping("/user")
public String updateUser(@RequestBody User user){
return user.toString();
}
/**
* @ApiImplicitParam 注解标注在方法上,用来描述方法的参数。其中 paramType 是指方法参数的类型,有如下可选值:
* path:参数获取方式为 @PathVariable
* query:参数获取方式为 @RequestParam
* header:参数获取方式为 @RequestHeader
* body
* form
*/
@ApiOperation(value ="查询用户", notes = "根据 id 查询用户")
@ApiImplicitParam(paramType = "path", name = "id", value = "用户 id", required = true)
@GetMapping("/user/{id}")
public String getUserById(@PathVariable Integer id){
return "查找的用户id是:" + id;
}
/**
* 如果有多个参数,可以将多个参数的 @ApiImplicitParam 注解放到 @ApiImplicitParams 中
*/
@ApiOperation(value = "新增用户", notes = "根据传入的用户名和密码添加一个新用户")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", name = "username",
value = "用户名", required = true, defaultValue = "test"),
@ApiImplicitParam(paramType = "query", name = "password",
value = "密码", required = true, defaultValue = "123")
})
@PostMapping("/user")
public String addUser(@RequestParam String username, @RequestParam String password) {
return "新增用户:" + username + " " + password;
}
/**
* @ApiResponse 是对响应结果的描述。code 表示响应码,message 为相应的描述信息。如果有多个 @ApiResponse,则放在一个 @ApiResponses 中
*/
@ApiOperation(value = "删除用户", notes = "根据 id 删除用户")
@ApiResponses({
@ApiResponse(code = 200, message = "删除成功!"),
@ApiResponse(code = 500, message = "删除失败!")
})
@DeleteMapping("/user/{id}")
public Integer deleteUserById(@PathVariable Integer id) {
return id;
}
/**
* @ApiIgnore 注解表示不对某个接口生成文档。
*/
@ApiIgnore
@GetMapping("/user/test")
public String test() {
return "这是一个测试接口,不需要在api文档中显示。";
}
}
🌵测试结果
启动打开链接:http://127.0.0.1:8080/swagger-ui/index.html
打开链接:http://127.0.0.1:8080/doc.html