为什么Spring的FactoryBean getObject返回null? [英] Why does a Spring's FactoryBean getObject return null?

查看:227
本文介绍了为什么Spring的FactoryBean getObject返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义 Converter 创建一个Spring ConversionService ,但返回值 ConversionServiceFactoryBean#getObject null 。参见示例:

I want to create a Spring ConversionService with custom Converters, but the return value of ConversionServiceFactoryBean#getObject is null. See example:

@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 。按预期注入转换器。为什么工厂返回 null ?我该如何解决?

checkNotNull throws a NullPointerException. The converters are injected as expected. Why does the factory return null? How can I fix that?

推荐答案

感谢 Sotirios Delimanolis #comment79692260_46364012>评论我找到了以下解决方案:

Thanks to the comment of Sotirios Delimanolis I came to the following solution:

@Bean
public ConversionServiceFactoryBean conversionService(Set<Converter<?, ?>> converters) {
    final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
    factory.setConverters(converters);
    return factory;
}

这实际上是以下配置的简写:

This is essentially a shorthand for the following configuration:

@Bean
public ConversionService conversionService(Set<Converter<?, ?>> converters) {
    final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
    factory.setConverters(converters);
    factory.afterPropertiesSet(); // necessary
    return factory.getObject();
}

工厂保持未完成状态,直到 afterPropertiesSet 解释)被调用。但是,如果返回 ConversionServiceFactoryBean 本身而不是 ConversionService ,则不需要调用它。由于工厂是 InitializingBean FactoryBean Spring将调用 afterPropertiesSet getObject

The factory remains in an unfinished state until afterPropertiesSet (explanation) is called. However, one doesn't need to call it, if the ConversionServiceFactoryBean itself is returned instead of the ConversionService. Since the factory is a InitializingBean and a FactoryBean Spring will call afterPropertiesSet and getObject internally, if a ConversionService instance is needed.

这篇关于为什么Spring的FactoryBean getObject返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆