我想创建一个包含自定义ConversionService
的Spring Converter
,但ConversionServiceFactoryBean#getObject
的返回值为null
。见例:
@Bean
@Autowired
public ConversionService conversionService(Set<Converter<?, ?>> converters) {
final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
factory.setConverters(converters);
return checkNotNull(
factory.getObject(),
"conversionService must not be null.");
}
checkNotNull
会抛出NullPointerException
。按预期注入converters
。为什么工厂返回null
?我该如何解决这个问题?
答案 0 :(得分:1)
感谢comment的Sotirios Delimanolis,我找到了以下解决方案:
@Bean
public ConversionServiceFactoryBean conversionService(Set<Converter<?, ?>> converters) {
final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
factory.setConverters(converters);
return factory;
}
这实际上是以下配置的简写:
@Bean
public ConversionService conversionService(Set<Converter<?, ?>> converters) {
final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
factory.setConverters(converters);
factory.afterPropertiesSet(); // necessary
return factory.getObject();
}
在调用afterPropertiesSet
(explanation)之前,工厂仍处于未完成状态。但是,如果返回ConversionServiceFactoryBean
本身而不是ConversionService
,则无需调用它。由于工厂是InitializingBean
,FactoryBean
Spring将在内部调用afterPropertiesSet
和getObject
,如果需要ConversionService实例。