如何使用 java config 配置 Spring ConversionService? [英] How to configure Spring ConversionService with java config?

查看:21
本文介绍了如何使用 java config 配置 Spring ConversionService?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的xml:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="converters.AddressToStringConverter" />
                <bean class="converters.StringToAddressConverter" />
            </list>
        </property>
    </bean>

它可以毫无问题地配置转换器.

It configures converters without problems.

但是此代码无法使相同:

But then this code fails to make the same:

@Configuration
public class ConversionConfiguration {

    @Bean
    public ConversionService getConversionService() {
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
        bean.setConverters(getConverters());
        bean.afterPropertiesSet();
        ConversionService object = bean.getObject();
        return object;
    }

    private Set<Converter> getConverters() {
        Set<Converter> converters = new HashSet<Converter>();

        converters.add(new AddressToStringConverter());
        converters.add(new StringToAddressConverter());

        return converters;
    }
}

这段配置被上下文扫描 - 我用调试器检查了它.问题出在哪里?

This piece of configuration gets scanned by context - I checked it with debugger. Where could be the problem?

推荐答案

在我看来,您的问题是 Bean 名称.一旦您没有使用 @Bean(name="conversionService") 显式设置名称,将使用的名称是 getConversionService.

From my point of view your problem is the Bean name. Once you don't explicit set the name using @Bean(name="conversionService") the name that will be used is getConversionService.

来自 文档:

这个 bean 的名称,或者如果是复数,则是这个 bean 的别名.如果离开未指定 bean 的名称是带注释的方法的名称.如果指定,方法名称将被忽略.

The name of this bean, or if plural, aliases for this bean. If left unspecified the name of the bean is the name of the annotated method. If specified, the method name is ignored.

这篇关于如何使用 java config 配置 Spring ConversionService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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