Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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<ModelConverter>): 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<String> {
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<KAnnotatedElement>(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<String>()
val mappedKotlinNames = HashSet<String>()
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"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> = 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
}
Original file line number Diff line number Diff line change
@@ -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<KotlinDefaultValueOptionalPropertyCustomizer>()
.forEach { modelConverters.removeConverter(it) }
}
}

@SpringBootApplication
@ComponentScan(basePackages = ["org.springdoc", "test.org.springdoc.api.v31.app28"])
class DemoApplication
}
Loading