为什么Spring的FactoryBean getObject返回null?

时间:2017-09-22 11:45:35

标签: java spring

我想创建一个包含自定义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?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

感谢commentSotirios 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();
}

在调用afterPropertiesSetexplanation)之前,工厂仍处于未完成状态。但是,如果返回ConversionServiceFactoryBean本身而不是ConversionService,则无需调用它。由于工厂是InitializingBeanFactoryBean Spring将在内部调用afterPropertiesSetgetObject,如果需要ConversionService实例。