1. 引入依赖 (pom.xml)
这是唯一需要的依赖,它包含了自动配置和 UI 界面:
XML
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
2. 基础配置 (application.properties)
你可以在配置文件中自定义 Swagger 路径(可选,不配置则使用默认):
bash
# 可选:自定义 API 文档路径
springdoc.api-docs.path=/v3/api-docs
# 可选:自定义 Swagger UI 路径
springdoc.swagger-ui.path=/swagger-ui.html
3. 高级配置类 (SwaggerConfig.java)
创建一个配置类,定义文档的头部信息(如标题、作者),并配置文件上传的支持(这是很多人容易忽略的点):
java
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.RequestBody;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
@Configuration
public class SwaggerConfig {
/**
* 配置 API 文档基本信息
*/
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("用户中心 API 文档")
.version("1.0")
.description("这是一个演示用户信息上传和头像管理的接口文档")
.contact(new Contact()
.name("开发团队")
.email("dev@example.com")));
}
/**
* 【关键】定制化:让 Swagger UI 支持 MultipartFile (文件上传) 的参数展示
* 如果你有文件上传接口,必须加这个 Bean,否则 Swagger 页面可能不会显示 "Choose File" 按钮
*/
@Bean
public OperationCustomizer operationCustomizer() {
return (operation, handlerMethod) -> {
// 识别方法中包含 MultipartFile 参数的接口
if (handlerMethod.getMethodParameters().length > 0) {
for (var param : handlerMethod.getMethodParameters()) {
if (MultipartFile.class.equals(param.getParameterType())) {
// 手动构建 RequestBody,强制指定为 multipart/form-data
RequestBody requestBody = new RequestBody();
Content content = new Content();
MediaType mediaType = new MediaType();
Schema<?> schema = new Schema<>().type("object");
// 这里的属性名要和 Controller 里的 @RequestParam 一致
schema.addProperty("username", new Schema<>().type("string").description("用户名"));
schema.addProperty("avatar", new Schema<>().type("string").format("binary").description("头像文件"));
mediaType.setSchema(schema);
content.addMediaType("multipart/form-data", mediaType);
requestBody.setContent(content);
requestBody.setRequired(true);
operation.setRequestBody(requestBody);
break;
}
}
}
return operation;
};
}
}
4. 启动并访问
-
启动 Spring Boot 应用。
-
打开浏览器访问:
-
你会看到一个漂亮的 UI 界面,找到
/api/user/upload接口,点击 "Try it out"。 -
输入
username,并点击 "Choose File" 选择一张图片,最后点击 "Execute" 即可直接在页面上测试接口。