Why does a Spring's FactoryBean getObject return null?

前端 未结 1 662
心在旅途
心在旅途 2021-01-22 01:54

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

1条回答
  •  有刺的猬
    2021-01-22 02:09

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

    @Bean
    public ConversionServiceFactoryBean conversionService(Set> 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> converters) {
        final ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
        factory.setConverters(converters);
        factory.afterPropertiesSet(); // necessary
        return factory.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.

    0 讨论(0)
提交回复
热议问题