Spring Boot集成SpringDoc生成Api文档
以下以 Maven 为例介绍 Spring Boot集成SpringDoc生成Api文档。
- 添加依赖
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
</dependency>
- 配置 annotationProcessor,实现通过 javadoc 生成文档。
每个 maven 模块都需要配置:
<properties>
<therapi-runtime-javadoc.version>0.15.0</therapi-runtime-javadoc.version>
<maven-compiler-plugin.version>3.13.0</maven-compiler-plugin.version>
</properties>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<annotationProcessorPaths>
<!-- https://springdoc.org/#javadoc-support -->
<path>
<groupId>com.github.therapi</groupId>
<artifactId>therapi-runtime-javadoc-scribe</artifactId>
<version>${therapi-runtime-javadoc.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
- 配置 spring boot 插件,生成 build.properties
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
- 自动装配
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = SPRINGDOC_ENABLED, matchIfMissing = true)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class SpringdocConfig {
@Value("${server.port}")
private String port;
@Value("${openapi.prod-url:https://localhost}")
private String prodUrl;
@Bean
public OpenAPI openAPI() {
Server devServer = new Server();
devServer.setUrl("http://localhost:" + port);
devServer.setDescription("Server URL in Development environment");
Server prodServer = new Server();
prodServer.setUrl(prodUrl);
prodServer.setDescription("Server URL in Production environment");
Contact contact = new Contact();
contact.setEmail("[email protected]");
contact.setName("ChenSoul");
contact.setUrl("https://blog.chensoul.cc");
License mitLicense = new License().name("Apache License").url("https://www.apache.org/licenses/LICENSE-2.0.txt");
Info info = new Info()
.title("Spring Boot3 Monolith API")
.version("1.0")
.contact(contact)
.description("This API exposes endpoints to manage charging sessions.").termsOfService("https://blog.chensoul.cc/terms")
.license(mitLicense);
return new OpenAPI().info(info).servers(List.of(devServer, prodServer));
}
}
Related content
- Spring Boot Tutorials
- [译]Spring Security 和 JWT 入门
- [译]测试 Spring Boot 应用程序:最佳实践和框架
- Spring Boot项目创建Docker镜像并运行应用
- [译]OAuth2 with Spring 第1部分:了解基本概念
- [译]OAuth2 with Spring 第2部分:授权服务器入门
- [译]OAuth2 with Spring 第3部分:使用Spring授权服务器授予authorization_code OIDC客户端
- [译]OAuth2 with Spring 第4部分:Spring授权客户端与Google授权服务器的社交登录演示
- [译]OAuth2 with Spring 第5部分:使用PKCE保护您的Spring Boot应用程序以增强安全性
- [译]使用 Spring Boot 构建 RESTful API:集成 DDD 和六边形架构