OpenAPI3&Spring Boot 自定义配置
- DocProperties
- DocConfiguration
- pom.xml
- application.yaml
DocProperties
@Data
@ConfigurationProperties("doc.info")
public class DocProperties {
private String group = "default";
private String title = "API";
private String description = "RESTFUL API";
private String version = "v2.0.0";
private String serverUrl;
private String license = "Apache 2.0";
private String licenseUrl = "https://www.apache.org/licenses/LICENSE-2.0.html";
private List globalParameter;
}
DocConfiguration
@Slf4j
@AllArgsConstructor
@EnableConfigurationProperties(DocProperties.class)
public class DocConfiguration {
private final DocProperties docProperties;
@Bean
public GroupedOpenApi api() {
return GroupedOpenApi.builder()
.group(docProperties.getGroup())
.pathsToMatch("
@Bean
public OpenAPI openApi() {
return new OpenAPI()
.info(new Info()
.title(docProperties.getTitle())
.description(docProperties.getDescription())
.version(docProperties.getVersion())
.license(new License().name(docProperties.getLicense()).url(docProperties.getLicenseUrl())))
// 配置接口访问地址
.servers(Collections.singletonList(new Server().url(docProperties.getServerUrl())))
// 配置认证
.security(Collections.singletonList(new SecurityRequirement().addList("Bearer Authorization")))
.components(this.components());
}
private Components components() {
Components components = new Components()
.addSecuritySchemes("Bearer Authorization", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))
.addSecuritySchemes("Basic Authorization", new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("basic"));
docProperties.getGlobalParameter()
.forEach(parameter -> components.addParameters(parameter.getName(), parameter));
return components;
}
}
pom.xml
1.6.8
org.springframework.boot
spring-boot-configuration-processor
true
org.springframework.boot
spring-boot-autoconfigure
org.springdoc
springdoc-openapi-ui
${springdoc.version}
application.yaml
doc:
info:
title: '系统管理服务'
description: '系统管理服务 RESTFUL API'
server-url: ${DOC_SERVER_URL:http://127.0.0.1:${server.port}}
global-parameter:
- name: 'realm'
in: 'header'
schema:
type: 'string'