java 如何在 springboot 中的 ConversionService 中自动装配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30039619/
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-11-02 16:20:34  来源:igfitidea点击:

How to Autowired in ConversionService in springboot

javaspringspring-mvcspring-boot

提问by lumi

Trying to access the ConversionControl in model in springboot, no luck.

试图在 springboot 中访问模型中的 ConversionControl,没有运气。

@Component
public class CityHelperService  {

    @Autowired
    ConversionService conversionService;// = ConversionServiceFactory.registerConverters();

    public City toEntity(CityDTO dto){
        City entity = conversionService.convert(dto, City.class);
        return entity;
    }

    public CityDTO toDTO(City entity){
        CityDTO dto = conversionService.convert(entity, CityDTO.class);
        return dto;
    }
}

It shows the following error:

它显示以下错误:

Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.lumiin.mytalk.model.CityModel com.lumiin.mytalk.controllers.CityController.cityModel;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cityModel' defined in file : Unsatisfied dependency expressed through constructor argument with index 1 of type [com.lumiin.mytalk.dao.CityHelperService]: : Error creating bean with name 'cityHelperService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.core.convert.ConversionService com.lumiin.mytalk.dao.CityHelperService.conversionService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cityHelperService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.core.convert.ConversionService com.lumiin.mytalk.dao.CityHelperService.conversionService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

采纳答案by lmazgon

Apparently there is no ConversionServicebean available, judging by the last nested exception:

ConversionService从最后一个嵌套异常来看,显然没有可用的 bean:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

A look into the Spring documentationreveals, that you should declare a ConversionServicebean. In the XML configuration it would look like this:

查看Spring 文档显示,您应该声明一个ConversionServicebean。在 XML 配置中,它看起来像这样:

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="example.MyCustomConverter"/>
        </set>
    </property>
</bean>

And since you're using Spring Boot, I assume you are creating the context programatically, so you should create a method annotated with @Bean, which returns a ConverstionService, like this (explained here):

并且由于您使用的是 Spring Boot,我假设您正在以编程方式创建上下文,因此您应该创建一个用 注释的方法@Bean,它返回一个ConverstionService,像这样(在此处解释):

@Bean(name="conversionService")
public ConversionService getConversionService() {
    ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
    bean.setConverters(...); //add converters
    bean.afterPropertiesSet();
    return bean.getObject();
}

回答by vijay

Not totally agreed with the accepted answers, because there would be a default ConverstionServicenamed mvcConversionServiceso you would get duplicate bean exception. Instead addConverterto FormatterRegistry, here is the link for the part answer:

不完全同意接受的答案,因为会有一个默认ConverstionService命名,mvcConversionService所以你会得到重复的 bean 异常。相反addConverterFormatterRegistry,这里是链接了部分答案:

Java Config equivalent for conversionService / FormattingConversionServiceFactoryBean

等效于转换服务 / FormattingConversionServiceFactoryBean 的 Java 配置

Also you would need (in some cases) to define to at least an empty Componentfor ConversionService, something like below:

您还需要(在某些情况下)至少定义一个空的Componentfor ConversionService,如下所示:

@Component @Primary
public class MyConversionService extends DefaultConversionService implements ConversionService {
    // an empty ConversionService to initiate call to register converters
}

This is to force spring container to initiate a call to:

这是为了强制 spring 容器发起一个调用:

class WebMvcConfigurerAdapter {
    ...

    public void addFormatters(FormatterRegistry registry) {
         //registry.addConverter(...);
    }
}