如何使用 java config 配置 Spring ConversionService?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11273443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:29:17  来源:igfitidea点击:

How to configure Spring ConversionService with java config?

javaxmlspringconfiguration

提问by Tadas ?ubonis

I have such xml:

我有这样的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?

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

回答by Francisco Spaeth

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

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

From documentation:

文档

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.

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

回答by Dimitri

In SpringMVC you can extend WebMvcConfigurerAdapter and use it for Java based config. To register custom converters you can modify the "addFormatters"-Method like this

在 SpringMVC 中,您可以扩展 WebMvcConfigurerAdapter 并将其用于基于 Java 的配置。要注册自定义转换器,您可以像这样修改“addFormatters”-Method

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "..." })
public class ApplicationConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
    {
        configurer.enable();
    }

    @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver()
    {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void addFormatters(FormatterRegistry formatterRegistry)
    {
        formatterRegistry.addConverter(getMyConverter());
    }

    @Bean
    public StringToCounterConverter getMyConverter()
    {
        return new StringToCounterConverter();
    }

}

回答by steffen

When you enable logging, you'll see which Beans are created by Spring, as described here.

当您启用日志记录,你会看到其中豆类是由Spring创建,如所描述这里

Log configuration

日志配置

    <logger name="org.springframework.beans" level="DEBUG" />

Log output

日志输出

    DEBUG (AbstractAutowireCapableBeanFactory.java:458) - Finished creating instance of bean 'getConversionService'

I copy+pasted your code and it worked without changing the name. I injected the ConversionServiceas follows:

我复制+粘贴了你的代码,它在不更改名称的情况下工作。我注入ConversionService如下:

@Resource
private ConversionService conversionService;

This works because of Autowiring by type. So maybe you had two ConversionServicebeans.

这是因为Autowiring by type。所以也许你有两个ConversionService豆子。