From adb5c28d930082131e0d4d26beab4c714710b943 Mon Sep 17 00:00:00 2001 From: anastasiia-baboshina Date: Thu, 3 Dec 2026 21:02:55 +0100 Subject: [PATCH] Add opt-in customizer to drop Kotlin properties with a default value from required jackson-module-kotlin reports a non-null Kotlin property with a default value as required for serialization, so it was listed in the "required" array of the schema, although a client can omit it. Add KotlinDefaultValueOptionalPropertyCustomizer. It removes such properties from "required", keeps the ones marked with @Schema(requiredMode = REQUIRED) and maps Kotlin names to JSON names. It is disabled by default because a class used as a request and as a response has a single schema. Enable it with springdoc.model-converters.kotlin-default-value-optional-property-customizer.enabled=true Fixes #3463 --- .../SpringDocKotlinConfiguration.kt | 9 ++ ...nDefaultValueOptionalPropertyCustomizer.kt | 147 ++++++++++++++++++ .../properties/SpringDocConfigProperties.java | 53 +++++++ .../org/springdoc/core/utils/Constants.java | 5 + .../api/v31/app28/DefaultValueController.kt | 40 +++++ .../api/v31/app28/SpringDocApp28Test.kt | 50 ++++++ .../test/resources/results/3.1.0/app28.json | 72 +++++++++ 7 files changed, 376 insertions(+) create mode 100644 springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/KotlinDefaultValueOptionalPropertyCustomizer.kt create mode 100644 springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/DefaultValueController.kt create mode 100644 springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/SpringDocApp28Test.kt create mode 100644 springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/resources/results/3.1.0/app28.json diff --git a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocKotlinConfiguration.kt b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocKotlinConfiguration.kt index 51b054dff6..2149642658 100644 --- a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocKotlinConfiguration.kt +++ b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/configuration/SpringDocKotlinConfiguration.kt @@ -17,6 +17,7 @@ package org.springdoc.core.configuration import org.springdoc.core.converters.KotlinInlineClassUnwrappingConverter +import org.springdoc.core.customizers.KotlinDefaultValueOptionalPropertyCustomizer import org.springdoc.core.customizers.KotlinDeprecatedPropertyCustomizer import org.springdoc.core.customizers.KotlinNullablePropertyCustomizer import org.springdoc.core.customizers.KotlinxSerializationRequiredPropertyCustomizer @@ -81,6 +82,14 @@ class SpringDocKotlinConfiguration() { return KotlinNullablePropertyCustomizer(objectMapperProvider) } + @Bean + @Lazy(false) + @ConditionalOnMissingBean + @ConditionalOnProperty(name = [Constants.SPRINGDOC_KOTLIN_DEFAULT_VALUE_OPTIONAL_PROPERTY_CUSTOMIZER_ENABLED]) + fun kotlinDefaultValueOptionalPropertyCustomizer(objectMapperProvider: ObjectMapperProvider): KotlinDefaultValueOptionalPropertyCustomizer { + return KotlinDefaultValueOptionalPropertyCustomizer(objectMapperProvider) + } + @Bean @Lazy(false) @ConditionalOnMissingBean diff --git a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/KotlinDefaultValueOptionalPropertyCustomizer.kt b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/KotlinDefaultValueOptionalPropertyCustomizer.kt new file mode 100644 index 0000000000..c1934b3c94 --- /dev/null +++ b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/customizers/KotlinDefaultValueOptionalPropertyCustomizer.kt @@ -0,0 +1,147 @@ +/* + * Copyright 2019-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springdoc.core.customizers + +import io.swagger.v3.core.converter.AnnotatedType +import io.swagger.v3.core.converter.ModelConverter +import io.swagger.v3.core.converter.ModelConverterContext +import io.swagger.v3.oas.models.Components +import io.swagger.v3.oas.models.media.Schema +import org.springdoc.core.providers.ObjectMapperProvider +import tools.jackson.databind.JavaType +import kotlin.reflect.KAnnotatedElement +import kotlin.reflect.full.memberProperties +import kotlin.reflect.full.primaryConstructor +import kotlin.reflect.jvm.javaField +import kotlin.reflect.jvm.javaGetter + +/** + * Removes from the `required` list of a schema the properties of a Kotlin class whose primary + * constructor parameter has a default value. + * + * `jackson-module-kotlin` reports a non-null property with a default value as required for + * serialization, so it ends up in `required`, although a client may omit it and the default + * applies. This customizer lists such a property as optional. A property annotated with + * `@Schema(requiredMode = REQUIRED)` stays required. + * + * The schema of a class is built once, so a class used as a request and as a response gets the + * same `required` list: this customizer is disabled by default. + * + * See: https://github.com/springdoc/springdoc-openapi/issues/3463 + */ +class KotlinDefaultValueOptionalPropertyCustomizer( + private val objectMapperProvider: ObjectMapperProvider +) : ModelConverter { + + override fun resolve(type: AnnotatedType, context: ModelConverterContext, chain: Iterator): Schema<*>? { + if (!chain.hasNext()) + return null + val resolvedSchema = chain.next().resolve(type, context, chain) + val javaType = try { + objectMapperProvider.jsonMapper().constructType(type.type) + } catch (_: Exception) { + return resolvedSchema + } + val rawClass = javaType.rawClass + if (rawClass == null || rawClass.annotations.none { it.annotationClass.java.name == KOTLIN_METADATA }) + return resolvedSchema + val targetSchema = resolveTargetSchema(resolvedSchema, context) ?: return resolvedSchema + val required = targetSchema.required + if (required.isNullOrEmpty()) + return resolvedSchema + val optionalProperties = findOptionalProperties(javaType) + if (optionalProperties.isEmpty()) + return resolvedSchema + val remaining = required.filterNot { it in optionalProperties } + if (remaining.size != required.size) + targetSchema.required = remaining.ifEmpty { null } + return resolvedSchema + } + + /** + * Finds the JSON names of the properties that have a default value in the primary + * constructor and are not explicitly marked as required. + * + * @param javaType the java type of the model + * @return the names of the optional properties, possibly empty + */ + private fun findOptionalProperties(javaType: JavaType): Set { + val optionalKotlinNames = try { + val kotlinClass = javaType.rawClass.kotlin + val constructor = kotlinClass.primaryConstructor ?: return emptySet() + val propertiesByName = kotlinClass.memberProperties.associateBy { it.name } + constructor.parameters.mapNotNullTo(LinkedHashSet()) { parameter -> + if (!parameter.isOptional) + return@mapNotNullTo null + val property = parameter.name?.let { propertiesByName[it] } ?: return@mapNotNullTo null + val annotatedElements = listOf(parameter, property) + val annotations = annotatedElements.flatMap { it.annotations } + + listOfNotNull(property.javaField, property.javaGetter).flatMap { it.annotations.asList() } + val explicitlyRequired = annotations.any { + it is io.swagger.v3.oas.annotations.media.Schema && it.requiredMode == io.swagger.v3.oas.annotations.media.Schema.RequiredMode.REQUIRED + } + if (explicitlyRequired) null else property.name + } + } catch (_: Throwable) { + return emptySet() + } + if (optionalKotlinNames.isEmpty()) + return optionalKotlinNames + // The schema properties are keyed by their JSON names, which differ from the Kotlin + // names when renamed with @JsonProperty or @JsonNaming: map them through Jackson. + val definitions = try { + objectMapperProvider.jsonMapper()._serializationContext().introspectBeanDescription(javaType).findProperties() + } catch (_: Exception) { + return optionalKotlinNames + } + val result = LinkedHashSet() + val mappedKotlinNames = HashSet() + for (definition in definitions) { + if (definition.internalName in optionalKotlinNames) { + result.add(definition.name) + mappedKotlinNames.add(definition.internalName) + } + } + optionalKotlinNames.filterNotTo(result) { it in mappedKotlinNames } + return result + } + + /** + * Resolves the schema that carries the model's properties: the defined model of a + * `$ref`, or the resolved schema itself. + * + * @param resolvedSchema the resolved schema + * @param context the context + * @return the target schema + */ + private fun resolveTargetSchema(resolvedSchema: Schema<*>?, context: ModelConverterContext): Schema<*>? { + if (resolvedSchema == null) + return null + val ref = resolvedSchema.`$ref` + if (ref != null) + return context.definedModels[ref.removePrefix(Components.COMPONENTS_SCHEMAS_REF)] + return if (resolvedSchema.properties != null) resolvedSchema else null + } + + private companion object { + + /** + * The annotation Kotlin adds to every Kotlin class. + */ + const val KOTLIN_METADATA = "kotlin.Metadata" + } +} diff --git a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/SpringDocConfigProperties.java b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/SpringDocConfigProperties.java index cb25d2a940..82203d98e3 100644 --- a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/SpringDocConfigProperties.java +++ b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/properties/SpringDocConfigProperties.java @@ -1220,6 +1220,11 @@ public static class ModelConverters { */ private KotlinxSerializationRequiredPropertyCustomizer kotlinxSerializationRequiredPropertyCustomizer = new KotlinxSerializationRequiredPropertyCustomizer(); + /** + * The Kotlin default value optional property customizer. + */ + private KotlinDefaultValueOptionalPropertyCustomizer kotlinDefaultValueOptionalPropertyCustomizer = new KotlinDefaultValueOptionalPropertyCustomizer(); + /** * Gets deprecating converter. @@ -1293,6 +1298,24 @@ public void setKotlinNullablePropertyCustomizer(KotlinNullablePropertyCustomizer this.kotlinNullablePropertyCustomizer = kotlinNullablePropertyCustomizer; } + /** + * Gets Kotlin default value optional property customizer. + * + * @return the Kotlin default value optional property customizer + */ + public KotlinDefaultValueOptionalPropertyCustomizer getKotlinDefaultValueOptionalPropertyCustomizer() { + return kotlinDefaultValueOptionalPropertyCustomizer; + } + + /** + * Sets Kotlin default value optional property customizer. + * + * @param kotlinDefaultValueOptionalPropertyCustomizer the Kotlin default value optional property customizer + */ + public void setKotlinDefaultValueOptionalPropertyCustomizer(KotlinDefaultValueOptionalPropertyCustomizer kotlinDefaultValueOptionalPropertyCustomizer) { + this.kotlinDefaultValueOptionalPropertyCustomizer = kotlinDefaultValueOptionalPropertyCustomizer; + } + /** * Gets kotlinx.serialization required property customizer. * @@ -1360,6 +1383,36 @@ public void setEnabled(boolean enabled) { } } + /** + * The Kotlin default value optional property customizer. + */ + public static class KotlinDefaultValueOptionalPropertyCustomizer { + + /** + * Remove from the required properties the properties of Kotlin classes that have a + * default value in the primary constructor. + */ + private boolean enabled; + + /** + * Is enabled boolean. + * + * @return the boolean + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Sets enabled. + * + * @param enabled the enabled + */ + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + } + /** * The kotlinx.serialization required property customizer. * diff --git a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/utils/Constants.java b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/utils/Constants.java index 255ad4e57c..d76e90a892 100644 --- a/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/utils/Constants.java +++ b/springdoc-openapi-starter-common/src/main/java/org/springdoc/core/utils/Constants.java @@ -106,6 +106,11 @@ public final class Constants { */ public static final String SPRINGDOC_KOTLIN_NULLABLE_PROPERTY_CUSTOMIZER_ENABLED = "springdoc.model-converters.kotlin-nullable-property-customizer.enabled"; + /** + * The constant SPRINGDOC_KOTLIN_DEFAULT_VALUE_OPTIONAL_PROPERTY_CUSTOMIZER_ENABLED. + */ + public static final String SPRINGDOC_KOTLIN_DEFAULT_VALUE_OPTIONAL_PROPERTY_CUSTOMIZER_ENABLED = "springdoc.model-converters.kotlin-default-value-optional-property-customizer.enabled"; + /** * The constant SPRINGDOC_KOTLINX_SERIALIZATION_REQUIRED_PROPERTY_CUSTOMIZER_ENABLED. */ diff --git a/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/DefaultValueController.kt b/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/DefaultValueController.kt new file mode 100644 index 0000000000..c303d2acdf --- /dev/null +++ b/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/DefaultValueController.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2019-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package test.org.springdoc.api.v31.app28 + +import com.fasterxml.jackson.annotation.JsonProperty +import io.swagger.v3.oas.annotations.media.Schema +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RestController + +data class CreateThing( + val name: String, + val tags: List = emptyList(), + val note: String? = null, + @get:JsonProperty("renamed_default") + val renamedDefault: String = "", + @get:Schema(requiredMode = Schema.RequiredMode.REQUIRED) + val forced: String = "forced", +) + +@RestController +class DefaultValueController { + + @PostMapping("/things") + fun create(@RequestBody thing: CreateThing) = Unit +} diff --git a/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/SpringDocApp28Test.kt b/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/SpringDocApp28Test.kt new file mode 100644 index 0000000000..97a3636401 --- /dev/null +++ b/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/kotlin/test/org/springdoc/api/v31/app28/SpringDocApp28Test.kt @@ -0,0 +1,50 @@ +/* + * Copyright 2019-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package test.org.springdoc.api.v31.app28 + +import io.swagger.v3.core.converter.ModelConverters +import org.junit.jupiter.api.AfterAll +import org.springdoc.core.customizers.KotlinDefaultValueOptionalPropertyCustomizer +import org.springdoc.core.utils.Constants.SPRINGDOC_KOTLIN_DEFAULT_VALUE_OPTIONAL_PROPERTY_CUSTOMIZER_ENABLED +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.context.annotation.ComponentScan +import org.springframework.test.context.TestPropertySource +import test.org.springdoc.api.v31.AbstractKotlinSpringDocMVCTest + +@TestPropertySource(properties = ["$SPRINGDOC_KOTLIN_DEFAULT_VALUE_OPTIONAL_PROPERTY_CUSTOMIZER_ENABLED=true"]) +class SpringDocApp28Test : AbstractKotlinSpringDocMVCTest() { + + companion object { + + /** + * The model converters are shared by all the tests of the JVM: unregister the + * customizer, which is enabled by this test only. + */ + @JvmStatic + @AfterAll + fun unregisterCustomizer() { + val modelConverters = ModelConverters.getInstance(true) + modelConverters.converters + .filterIsInstance() + .forEach { modelConverters.removeConverter(it) } + } + } + + @SpringBootApplication + @ComponentScan(basePackages = ["org.springdoc", "test.org.springdoc.api.v31.app28"]) + class DemoApplication +} diff --git a/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/resources/results/3.1.0/app28.json b/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/resources/results/3.1.0/app28.json new file mode 100644 index 0000000000..35ac02afe0 --- /dev/null +++ b/springdoc-openapi-tests/springdoc-openapi-kotlin-webmvc-tests/src/test/resources/results/3.1.0/app28.json @@ -0,0 +1,72 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "OpenAPI definition", + "version": "v0" + }, + "servers": [ + { + "url": "http://localhost", + "description": "Generated server url" + } + ], + "paths": { + "/things": { + "post": { + "tags": [ + "default-value-controller" + ], + "operationId": "create", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateThing" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK" + } + } + } + } + }, + "components": { + "schemas": { + "CreateThing": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "note": { + "type": [ + "string", + "null" + ] + }, + "renamed_default": { + "type": "string" + }, + "forced": { + "type": "string" + } + }, + "required": [ + "forced", + "name" + ] + } + } + } +}