在Spring Boot中以编程方式注册Spring Converter

jpo*_*ete 10 java spring spring-mvc spring-boot

我想以编程方式在Spring Boot项目中注册Spring Converter.在过去的Spring项目中,我用这样的XML完成了它...

<!-- Custom converters to allow automatic binding from Http requests parameters to objects -->
<!-- All converters are annotated w/@Component -->
<bean id="conversionService"
      class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <ref bean="stringToAssessmentConverter" />
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

我试图找出如何在Spring Boot的SpringBootServletInitializer中做

更新:我通过传递StringToAssessmentConverter作为参数取得了一些进展getConversionService,但现在我收到了"No default constructor found"StringToAssessmentConverter类的错误.我不确定为什么Spring没有看到@Autowired构造函数.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    ...

    @Bean(name="conversionService")
    public ConversionServiceFactoryBean getConversionService(StringToAssessmentConverter stringToAssessmentConverter) {
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();

        Set<Converter> converters = new HashSet<>();

        converters.add(stringToAssessmentConverter);

        bean.setConverters(converters);
        return bean;
    }
}  
Run Code Online (Sandbox Code Playgroud)

这是转换器的代码......

 @Component
 public class StringToAssessmentConverter implements Converter<String, Assessment> {

     private AssessmentService assessmentService;

     @Autowired
     public StringToAssessmentConverter(AssessmentService assessmentService) {
         this.assessmentService = assessmentService;
     }

     public Assessment convert(String source) {
         Long id = Long.valueOf(source);
         try {
             return assessmentService.find(id);
         } catch (SecurityException ex) {
             return null;
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)

完全错误

Failed to execute goal org.springframework.boot:spring-boot-maven-
plugin:1.3.2.RELEASE:run (default-cli) on project yrdstick: An exception 
occurred while running. null: InvocationTargetException: Error creating 
bean with name
'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPo
stProcessor': Invocation of init method failed; nested exception is 
org.springframework.beans.factory.UnsatisfiedDependencyException: Error 
creating bean with name 'conversionService' defined in 
me.jpolete.yrdstick.Application: Unsatisfied dependency expressed through 
constructor argument with index 0 of type 
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: : Error 
creating bean with name 'stringToAssessmentConverter' defined in file 
[/yrdstick/target/classes/me/jpolete/yrdstick/websupport
/StringToAssessmentConverter.class]: Instantiation of bean failed; nested 
exception is org.springframework.beans.BeanInstantiationException: Failed 
to instantiate 
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: No default 
constructor found; nested exception is java.lang.NoSuchMethodException: 
me.jpolete.yrdstick.websupport.StringToAssessmentConverter.<init>(); 
nested exception is 
org.springframework.beans.factory.BeanCreationException: Error creating 
bean with name 'stringToAssessmentConverter' defined in file [/yrdstick
/dev/yrdstick/target/classes/me/jpolete/yrdstick/websupport
/StringToAssessmentConverter.class]: Instantiation of bean failed; nested 
exception is org.springframework.beans.BeanInstantiationException: Failed 
to instantiate 
[me.jpolete.yrdstick.websupport.StringToAssessmentConverter]: No default 
constructor found; nested exception is java.lang.NoSuchMethodException: 
me.jpolete.yrdstick.websupport.StringToAssessmentConverter.<init>()
Run Code Online (Sandbox Code Playgroud)

deF*_*tas 25

答案是,您只需要将转换器分配为@Component:

这是我的转换器示例

import org.springframework.core.convert.converter.Converter;
@Component
public class DateUtilToDateSQLConverter implements Converter<java.util.Date, Date> {

    @Override
    public Date convert(java.util.Date source) {
        return new Date(source.getTime());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后当Spring需要进行转换时,调用转换器.

我的春季版本: 1.4.1

  • [Spring Boot 2.2.4 文档](https://docs.spring.io/spring-boot/docs/2.2.4.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc -auto-configuration): “自动配置在 Spring 的默认设置之上添加了以下功能:自动注册 Converter、GenericConverter 和 Formatter beans。” (3认同)
  • 如果需要转换器将属性转换为特定对象,则将其注册为组件可能为时已晚。我正在 spring-boot-2.3.11 中使用并收到错误“找不到能够从类型 [java.lang.String] 转换为类型 [org.raisercostin.jedio.WritableDirLocation] 的转换器” (3认同)
  • 感谢您提到这一点。不幸的是,Spring文档中的任何地方都没有对此进行记录。 (2认同)

fg7*_*8nc 5

**如果您不在 Spring Boot 上,其中执行使用 @Component (和类似的构造型注释)注释的转换器的自动注册,并且您不在Web Mvc 环境中

@Bean
ConversionService conversionService(){
    ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean();
    Set<Converter<?, ?>> convSet = new HashSet<Converter<?, ?>>();
    convSet.add(new MyConverter()); // or reference bean convSet.add(myConverter());
    factory.setConverters(convSet);
    factory.afterPropertiesSet();
    return factory.getObject();
}
Run Code Online (Sandbox Code Playgroud)