我springdoc-openapi-ui在一个简单的 spring-boot 项目中使用1.4.0 版本(通过 Maven)中的 Java 库,没有任何自定义。
Swagger 页面在https://my-url.com/my-context-path/swagger-ui/index.html下生成
和https://my-url.com/my-context-path/v3/api-docs/下的 api-docs
这两个都有效,我可以联系到他们。到现在为止还挺好!
当简单地导航到https://my-url.com/my-context-path/swagger-ui.html 时,我得到一个 HTTP 状态 302 和一个location在响应头中设置的属性,它应该将我重定向到 swagger 页面从上面(我假设)。
但是,location属性中的 URL缺少上下文路径!它看起来像这样:https :
//my-url.com/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config
它重定向到一个不存在的页面,我收到 404 错误代码。请注意,configUrl 似乎也缺少上下文路径。
任何想法为什么会发生这种情况以及如何解决?
这个 Github 问题似乎是同样的问题,但最后声明问题已解决:https : //github.com/springdoc/springdoc-openapi/issues/37,这是针对比我更早的版本。
swagger swagger-ui springdoc springdoc-ui springdoc-openapi-ui
我想对Schemas为我的实体类生成的 DTO 类进行排序Springdoc ui。
我能够对文件中的tags和operations进行以下配置,yml但我的模式不是按排序顺序排列的。
springdoc:
swagger-ui:
disable-swagger-default-url: true
tags-sorter: alpha
operations-sorter: alpha
doc-expansion: none
Run Code Online (Sandbox Code Playgroud)
我怎样才能对我的模式进行排序。
谢谢。
我将此依赖项添加到我的 Spring Boot 应用程序中
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.3</version>
<type>pom.sha512</type>
</dependency>
Run Code Online (Sandbox Code Playgroud)
然后我就可以打开:https://localhost:8443/v3/api-docs
浏览器确实会询问我的凭据,只要我正确输入用户/密码,它就可以工作,但它会向我显示全局可用的所有方法。我只希望用户有权使用的方法显示在 api 文档中。
对于特定方法是使用此标签来授权我的调用:
@PreAuthorize("hasRole('USER') OR hasRole('ADMIN')")
这是我的网络安全配置类:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("user").password(new BCryptPasswordEncoder().encode("blabl")).roles("USER")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("blabla")).roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
Run Code Online (Sandbox Code Playgroud) 我已经使用 springboot 创建了rest webservice,并添加了 springdoc-open-api 用于 webservice 的文档,现在我有 2 个问题
1-如何将自定义测试值添加到显示在swagger-ui文档页面上的请求中?
2-如何在 swagger-ui 文档页面上单击“TRY IT OUT”按钮来执行请求?
请参考下面的代码片段来获取其余的网络服务:
@PostMapping(value="/result", consumes={ "application/json"},produces={ "application/json" } )
@Parameter(description = "Student object need to calculate the score" ,name="InputObject", required = true )
public ResponseEntity<Result> displayResult(@Valid @RequestBody Student request);
Public class Student{
String name;
String birthDate;
String motherName;
int rollNo;
int seatNo;
}
Public class Result{
int marks;
String grade;
double percentage;
}
I have tried to add value of request using @Schema(name = "name", example= …Run Code Online (Sandbox Code Playgroud) 为了改进我们的 api 文档,我想向响应正文的字段添加描述
作为示例,请参阅此处的默认 petstore 规范: https: //editor.swagger.io/
在宠物响应中的 POST /pet 中,状态的描述为“商店中的宠物状态”
如何从代码库中的注释角度做到这一点?
(昂首阔步v3)
Swagger 文档将持续时间显示为
"duration": {
"seconds": 0,
"nano": 0,
"zero": true,
"negative": true,
"units": [
{
"dateBased": true,
"timeBased": true,
"durationEstimated": true
}
]
},
Run Code Online (Sandbox Code Playgroud)
但实际的格式是 ISO 8601 持续时间格式(PT0S),以下是代码段。有没有办法正确格式化文档?
任务文件
@Document(collection = "tasks")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder(toBuilder = true)
public class Task {
public enum Status {
todo, inprogress, done
}
@Id
private String id;
private String name;
private String description;
private Status status = Status.todo;
private Duration estimatedDuration = Duration.ZERO;
private Duration duration = Duration.ZERO;
}
Run Code Online (Sandbox Code Playgroud)
初始化
@SpringBootApplication
@OpenAPIDefinition(info = …Run Code Online (Sandbox Code Playgroud) 我有一个带有@RequestBodyDTO 的控制器。我需要显示 DTO 的架构,而不是stringSwagger 中 RequestBody 架构中的默认架构。
通过在 API 之上使用 @Operation 并在其中使用 @Parameter,我已经能够在两个地方描述 DTO

并填写示例(参见代码)。我已经尝试@Schema过@Operation(在 requestBody 下)和@Parameter注释。前者抛出 NPE,后者不做任何改变,并针对 DTO 本身中的对应注释进行了各种尝试。
样品控制器
@RequestMapping(value = "/{myPathVar}", method = RequestMethod.POST)
@Operation(summary = "Create something.",
parameters = { @Parameter(in = ParameterIn.PATH, name = "myPathVar", description = "Some path variable. Swagger uses this description.") },
requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "My description here.",
content = @Content(examples = @ExampleObject("{\"A\" : \"a\",\"B\" : \"{\"b\" : \"foo\", \"bb\" …Run Code Online (Sandbox Code Playgroud) 我正在从 Springfox 3.0 切换到 OpenAPI 3.0 + Springdoc-openapi。
在 Springfox 中,标签顺序是按字母顺序排列的,但在 Springdoc 的 Swagger UI 中,顺序似乎是随机的。
如何控制 UI 上的标签顺序?我更喜欢自己选择的顺序,但也可以按标签名称的字母顺序排序。
@Tag(name = MY_CONTROLLER_TAG_NAME, description = MY_CONTROLLER_TAG_DESC)
public class MyController {
Run Code Online (Sandbox Code Playgroud)
<springdoc-openapi.version>1.6.4</springdoc-openapi.version>
...
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc-openapi.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
<version>${springdoc-openapi.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
springdoc:
show-actuator: ${SWAGGER_ENABLED:true}
swagger-ui:
doc-expansion: none
api-docs:
enabled: ${SWAGGER_ENABLED:true}
model-converters:
pageable-converter:
enabled: true
Run Code Online (Sandbox Code Playgroud) 我正在尝试让 Swagger UI 在我的项目中工作,并且正在遵循这些文档,但是无论我尝试什么,我的应用程序都会立即崩溃,并出现以下异常:
上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“securityConfig”的 bean 时出错:通过方法“setContentNegotationStrategy”参数 0 表示不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration”的 bean 时出错:通过方法“setConfigurers”参数 0 表示不满足的依赖关系;嵌套异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建类路径资源[org/springdoc/webmvc/ui/SwaggerConfig.class]中定义的名称为“swaggerWebMvcConfigurer”的bean时出错:通过方法“swaggerWebMvcConfigurer”参数1表达的依赖关系不满足; 嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:创建类路径资源 [org/springdoc/webmvc/ui/SwaggerConfig.class] 中定义的名称为“indexPageTransformer”的 bean 时出错:通过方法“indexPageTransformer”参数 3 表达的依赖关系不满足; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建在类路径资源 [org/springdoc/webmvc/ui/SwaggerConfig.class] 中定义的名为“swaggerWelcome”的 bean 时出错:合并 bean 定义的后处理失败;嵌套异常是 java.lang.IllegalStateException:无法从 ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7] 内省类 [org.springdoc.webmvc.ui.SwaggerWelcomeWebMvc]
我将 Kotlin 与 Spring Boot 结合使用,这些是我的 Gradle 依赖项:
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-jooq")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-configuration-processor")
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-log4j2")
implementation("com.braintreepayments.gateway:braintree-java:3.14.0")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.13.1")
implementation("com.fasterxml.jackson.core:jackson-databind:2.13.2")
implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.13.2")
implementation("org.apache.logging.log4j:log4j-layout-template-json")
implementation("org.springdoc:springdoc-openapi-kotlin:1.6.6")
implementation("org.springdoc:springdoc-openapi-ui:1.6.6")
implementation("org.jooq:jooq-meta")
implementation("org.jooq:jooq-kotlin")
implementation("org.jooq:jooq-codegen")
implementation("org.jooq:jooq-codegen-maven")
implementation("org.jooq:jooq-meta-extensions")
implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.10")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.6.10")
implementation("com.zaxxer:HikariCP:5.0.1")
implementation("com.github.ben-manes.caffeine:caffeine:3.0.5")
implementation("org.flywaydb:flyway-core:8.5.4")
implementation("org.postgresql:postgresql:42.3.3")
Run Code Online (Sandbox Code Playgroud)
我已经尝试了很多不同的包的很多不同的组合,但它总是会在启动时抛出异常。
Gradle 文件的插件部分:
plugins {
id("org.springframework.boot") version "3.0.0-SNAPSHOT"
id("io.spring.dependency-management") …Run Code Online (Sandbox Code Playgroud) 对于某些错误代码,我正在尝试向 API 中的所有端点添加默认错误模型。
我通过阅读以下问题找到了部分解决方案:
这是我为该定制创建的 bean:
@Bean
public OpenApiCustomiser customOpenApiCustomiser() {
return openApi -> {
openApi.getPaths().values().forEach(pathItem -> pathItem.readOperations().forEach(operation -> {
Schema sharedErrorSchema = ModelConverters.getInstance()
.read(Error.class)
.getOrDefault("Error", new Schema());
MediaType sharedMediaType = new MediaType().schema(sharedErrorSchema);
Content sharedContent = new Content()
.addMediaType(APPLICATION_JSON_VALUE, sharedMediaType);
ApiResponses apiResponses = operation.getResponses();
ApiResponse response = new ApiResponse()
.description("Unhandled server error")
.content(sharedContent);
apiResponses.addApiResponse("500", response);
}));
};
}
Run Code Online (Sandbox Code Playgroud)
我的 Error 类看起来像:
public class Error {
private String message;
private List<ErrorItem> errorItems;
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我在 swagger-ui 中打开端点定义之一时,出现以下错误:
Could …
spring-boot ×6
java ×4
swagger ×4
swagger-ui ×4
openapi ×3
springdoc ×3
spring ×2
springdoc-ui ×2
duration ×1
kotlin ×1
rest ×1