java 如何在 Spring Boot 中注册自定义转换器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34239585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:38:47  来源:igfitidea点击:

How to register custom converters in spring boot?

javaspringspring-bootspring-data

提问by

I writing application using spring-boot-starter-jdbc (v1.3.0).

我使用 spring-boot-starter-jdbc (v1.3.0) 编写应用程序。

The problem that I met: Instance of BeanPropertyRowMapperfails as it cannot convert from java.sql.Timestampto java.time.LocalDateTime.

我遇到的问题:的实例BeanPropertyRowMapper,因为它无法从转换失败java.sql.Timestampjava.time.LocalDateTime

In order to copy this problem, I implemented org.springframework.core.convert.converter.Converterfor these types.

为了复制这个问题,我org.springframework.core.convert.converter.Converter为这些类型实现 了。

public class TimeStampToLocalDateTimeConverter implements Converter<Timestamp, LocalDateTime> {

    @Override
    public LocalDateTime convert(Timestamp s) {
        return s.toLocalDateTime();
    }
}

My question is: How do I make available TimeStampToLocalDateTimeConverterfor BeanPropertyRowMapper.

我的问题是:如何让我提供TimeStampToLocalDateTimeConverterBeanPropertyRowMapper

More general question, how do I register my converters, in order to make them available system wide?

更一般的问题,我如何注册我的转换器,以使它们在系统范围内可用?

The following code bring us to NullPointerExceptionon initialization stage:

以下代码将我们带到NullPointerException初始化阶段:

private Set<Converter> getConverters() {
    Set<Converter> converters = new HashSet<Converter>();
    converters.add(new TimeStampToLocalDateTimeConverter());
    converters.add(new LocalDateTimeToTimestampConverter());

    return converters;
}

@Bean(name="conversionService")
public ConversionService getConversionService() {
    ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
    bean.setConverters(getConverters()); 
    bean.afterPropertiesSet();
    return bean.getObject();
}    

Thank you.

谢谢你。

回答by Balaji Murugesan

All custom conversion service has to be registered with the FormatterRegistry. Try creating a new configuration and register the conversion service by implementing the WebMvcConfigurer

所有自定义转换服务都必须在 FormatterRegistry 中注册。尝试创建一个新的配置并通过实现 WebMvcConfigurer 来注册转换服务

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addallFormatters(FormatterRegistry registry) {
        registry.addConverter(new TimeStampToLocalDateTimeConverter());
    }
}

Hope this works.

希望这有效。

回答by SauriBabu

org.springframework.web.servlet.config.annotation.WebMvcConfigureror any on its implementation is one stop place for any kind of customization in spring boot project. It prvoides various methods, for your Converter requirement.

org.springframework.web.servlet.config.annotation.WebMvcConfigurer或其实现中的任何一个都是 Spring Boot 项目中任何类型定制的一站式场所。它提供了各种方法,以满足您的转换器要求。

Just create a new Converter by extending org.springframework.core.convert.converter.Converter<S, T>. Then register it with Spring by your class overriding method org.springframework.web.servlet.config.annotation.WebMvcConfigurer.addFormatters(FormatterRegistry)

只需通过扩展创建一个新的转换器org.springframework.core.convert.converter.Converter<S, T>。然后通过您的类覆盖方法将其注册到 Springorg.springframework.web.servlet.config.annotation.WebMvcConfigurer.addFormatters(FormatterRegistry)

Note there are Other types of Converter also which basically starts from ConditionalConverter.

请注意,还有其他类型的转换器,它们基本上都是从 ConditionalConverter 开始的。

回答by s10z

I suggest to use @Autowired and the related dependency injection mechanism of spring to use a single ConversionService instance throughout your application. The ConversionService will be instantiated within the configuration.

我建议使用 @Autowired 和 spring 的相关依赖注入机制在整个应用程序中使用单个 ConversionService 实例。ConversionService 将在配置中实例化。

All Converters to be available application wide receive an annotation (e.g. @AutoRegistered). On application start a @Component FormatterRegistrar (Type name itself is a bit misleading, yes it is "...Registrar" as it does the registering. And @Component as it is fully spring managed and requires dependency injection) will receive @AutoRegistered List of all annotated Converters.

所有在应用程序范围内可用的转换器都会收到一个注释(例如@AutoRegistered)。在应用程序启动时,@Component FormatterRegistrar(类型名称本身有点误导,是的,它是“...Registrar”,因为它进行注册。而 @Component 因为它是完全由 spring 管理的并且需要依赖注入)将收到 @AutoRegistered List所有带注释的转换器。

See this thread for concrete implementation details. We use this mechanism within our project and it works out like a charm.

有关具体实现细节,请参阅此线程 。我们在我们的项目中使用这种机制,它就像一个魅力。

回答by Ankit Bansal

Trying adding

尝试添加

@Converter(autoApply = true)

Its needs to be placed over the convertor class. This works for me in case of Convertor needed for Localdate for interacting to DB.

它需要放在转换器类上。如果Localdate需要Convertor与DB交互,这对我有用。

@Converter(autoApply = true)
public class LocalDateAttributeConverter implements AttributeConverter<LocalDate, Date> {

    @Override
    public Date convertToDatabaseColumn(LocalDate locDate) {
      return (locDate == null ? null : Date.valueOf(locDate));
    }

    @Override
    public LocalDate convertToEntityAttribute(Date sqlDate) {
      return (sqlDate == null ? null : sqlDate.toLocalDate());
    }
}

This is now applied automatically while interacting with DB.

这现在在与数据库交互时自动应用。