From 65257d983bba55137159d940c87d6c3b0faf5c8f Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Wed, 12 Mar 2025 13:55:53 +0100 Subject: [PATCH] =?UTF-8?q?Introduce=20`CustomConversions.getRequiredValue?= =?UTF-8?q?Converter(=E2=80=A6)`.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provide convenience method to simplify flow in calling code. See #3170 --- .../data/convert/CustomConversions.java | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/springframework/data/convert/CustomConversions.java b/src/main/java/org/springframework/data/convert/CustomConversions.java index 8e5dbd583..f70cb37c6 100644 --- a/src/main/java/org/springframework/data/convert/CustomConversions.java +++ b/src/main/java/org/springframework/data/convert/CustomConversions.java @@ -185,9 +185,36 @@ public class CustomConversions { */ public boolean hasValueConverter(PersistentProperty property) { - PropertyValueConversions propertyValueConversions = getPropertyValueConversions(); + PropertyValueConversions pvc = getPropertyValueConversions(); - return propertyValueConversions != null && propertyValueConversions.hasValueConverter(property); + return pvc != null && pvc.hasValueConverter(property); + } + + /** + * Returns the required {@link PropertyValueConverter} for the given {@link PersistentProperty} or throws + * {@link IllegalStateException} if no converter is available. This is a convenience method for + * {@code getPropertyValueConversions().getValueConverter(…)} enforcing non-null constraints. + *

+ * Prior to calling this method you should verify a converter is available using + * {@link #hasValueConverter(PersistentProperty)}. + * + * @param property {@link PersistentProperty} to evaluate; must not be {@literal null}. + * @return the required {@link PropertyValueConverter} + * @throws IllegalStateException if no converter is available. + * @since 4.0 + * @see #hasValueConverter(PersistentProperty) + */ + public , VCC extends ValueConversionContext

> PropertyValueConverter getRequiredValueConverter( + P property) { + + PropertyValueConversions pvc = getPropertyValueConversions(); + PropertyValueConverter converter = pvc != null ? pvc.getValueConverter(property) : null; + + if (converter == null) { + throw new IllegalStateException("No value converter registered for property %s".formatted(property.getName())); + } + + return converter; } /**