Spring ConversionService adding Converters

后端 未结 9 801
别那么骄傲
别那么骄傲 2020-12-31 03:47

I searched for the below problem, but couldn\'t find an answer.

I want to use spring\'s conversion service by writing my custom converter that implements org.spri

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 04:39

    To resolve any circular dependencies, here the steps I followed (Spring Boot v5.2.1):

    Register a simple conversionService

    @Configuration
    public class ConverterProvider {
    
        @Bean
        public ConversionService conversionService() {
            ConversionService conversionService = new GenericConversionService();
            return conversionService;
        }
    }
    

    Inject your custom converters

    @Component
    public class ConvertersInjection {
    
        @Autowired
        private GenericConversionService conversionService;
    
        @Autowired
        private void converters(Set converters) {
            converters.forEach(conversionService::addConverter);
        }
    }
    

    The converter can even autowire your conversionService

    @Component
    public class PushNotificationConverter implements Converter {
        @Lazy
        @Autowired
        private ConversionService conversionService;
    
        @Override
        public GCM convert(PushNotificationMessages.PushNotification source) {
            GCM gcm = new GCM();
            if (source.hasContent()) {
                PushNotificationMessages.PushNotification.Content content = source.getContent();
                if (content.hasData()) {
                    conversionService.convert(content.getData(), gcm.getData().getClass());
                } else if (content.hasNotification()) {
                    conversionService.convert(content.getNotification(), gcm.getNotification().getClass());
                }
            }
            return gcm;
        }
    }
    

提交回复
热议问题