11package org .springframework .boot .context .properties ;
22
3+ import java .util .List ;
34import lombok .RequiredArgsConstructor ;
45import org .springframework .context .ApplicationContext ;
56import org .springframework .core .convert .ConversionService ;
7+ import org .springframework .core .convert .ConverterNotFoundException ;
8+ import org .springframework .core .convert .TypeDescriptor ;
9+ import org .springframework .lang .Nullable ;
10+ import org .springframework .util .Assert ;
611
712/**
813 * Provides an access to {@link ConversionServiceDeducer} to retrieve {@link ConversionService}.
@@ -13,6 +18,41 @@ public class ConversionServiceRetriever {
1318 private final ApplicationContext applicationContext ;
1419
1520 public ConversionService getConversionService () {
16- return new ConversionServiceDeducer (this .applicationContext ).getConversionService ();
21+ return new ComposedConversionService (
22+ new ConversionServiceDeducer (this .applicationContext ).getConversionServices ());
23+ }
24+
25+ @ RequiredArgsConstructor
26+ private class ComposedConversionService implements ConversionService {
27+
28+ private final List <ConversionService > conversionServices ;
29+
30+ @ Override
31+ public boolean canConvert (@ Nullable Class <?> sourceType , Class <?> targetType ) {
32+ return conversionServices .stream ()
33+ .anyMatch (cs -> cs .canConvert (sourceType , targetType ));
34+ }
35+
36+ @ Override
37+ public boolean canConvert (@ Nullable TypeDescriptor sourceType , TypeDescriptor targetType ) {
38+ return conversionServices .stream ()
39+ .anyMatch (cs -> cs .canConvert (sourceType , targetType ));
40+ }
41+
42+ @ Override
43+ public <T > T convert (@ Nullable Object source , Class <T > targetType ) {
44+ Assert .notNull (targetType , "Target type to convert to cannot be null" );
45+ return (T ) convert (source , TypeDescriptor .forObject (source ), TypeDescriptor .valueOf (targetType ));
46+ }
47+
48+ @ Override
49+ public Object convert (@ Nullable Object source , @ Nullable TypeDescriptor sourceType , TypeDescriptor targetType ) {
50+ Assert .notNull (targetType , "Target type to convert to cannot be null" );
51+ return conversionServices .stream ()
52+ .filter (cs -> cs .canConvert (sourceType , targetType ))
53+ .findAny ()
54+ .map (cs -> cs .convert (source , sourceType , targetType ))
55+ .orElseThrow (() -> new ConverterNotFoundException (sourceType , targetType ));
56+ }
1757 }
1858}
0 commit comments