如何在弹簧靴中注册自定义转换器? [英] How to register custom converters in spring boot?
问题描述
我使用spring-boot-starter-jdbc(v1.3.0)编写应用程序。
I writing application using spring-boot-starter-jdbc (v1.3.0).
我遇到的问题: BeanPropertyRowMapper
的实例失败,因为它无法从 java转换.sql.Timestamp
到 java.time.LocalDateTime
。
The problem that I met: Instance of BeanPropertyRowMapper
fails as it cannot convert from java.sql.Timestamp
to java.time.LocalDateTime
.
为了复制这个问题,我实现了
org.springframework.core.convert.converter.Converter
对于这些类型。
In order to copy this problem, I implemented
org.springframework.core.convert.converter.Converter
for these types.
public class TimeStampToLocalDateTimeConverter implements Converter<Timestamp, LocalDateTime> {
@Override
public LocalDateTime convert(Timestamp s) {
return s.toLocalDateTime();
}
}
我的问题是:我如何提供 TimeStampToLocalDateTimeConverter
for BeanPropertyRowMapper
。
My question is: How do I make available TimeStampToLocalDateTimeConverter
for BeanPropertyRowMapper
.
更一般的问题,我该怎么办?注册我的转换器,以使它们在系统范围内可用?
More general question, how do I register my converters, in order to make them available system wide?
以下代码在初始化阶段将我们带到 NullPointerException
:
The following code bring us to NullPointerException
on initialization stage:
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();
}
谢谢。
推荐答案
我建议使用@Autowired和spring的相关依赖注入机制在整个应用程序中使用单个ConversionService实例。 ConversionService将在配置中实例化。
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.
所有应用程序范围内可用的转换器都会收到注释(例如@AutoRegistered)。在应用程序启动@Component FormatterRegistrar(类型名称本身有点误导,是的,它是...注册器,因为它进行注册。而@Component因为它是完全弹簧管理并需要依赖注入)将接收@AutoRegistered列表所有带注释的转换器。
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.
请参阅此主题以获取具体实施细节。我们在项目中使用这种机制,它就像一个魅力。
See this thread for concrete implementation details. We use this mechanism within our project and it works out like a charm.
这篇关于如何在弹簧靴中注册自定义转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!