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

我想以编程方式在Spring Boot项目中注册Spring Converter。 在过去的Spring项目中,我用XML这样做了……

         

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

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

 @SpringBootApplication public class Application extends SpringBootServletInitializer { ... @Bean(name="conversionService") public ConversionServiceFactoryBean getConversionService(StringToAssessmentConverter stringToAssessmentConverter) { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); Set converters = new HashSet(); converters.add(stringToAssessmentConverter); bean.setConverters(converters); return bean; } } 

这是转换器的代码……

  @Component public class StringToAssessmentConverter implements Converter { 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; } } } 

完全错误

 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.(); 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.() 

答案是,您只需要将转换器旋转为@Component

这是我的转换器示例

 import org.springframework.core.convert.converter.Converter; @Component public class DateUtilToDateSQLConverter implements Converter { @Override public Date convert(java.util.Date source) { return new Date(source.getTime()); } } 

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

我的Spring Boot版本: 1.4.1

这是我的解决方案:

TypeConverter注释:

 @Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface TypeConverter { } 

转换注册商:

 @Configuration public class ConverterConfiguration { @Autowired(required = false) @TypeConverter private Set> autoRegisteredConverters; @Autowired(required = false) @TypeConverter private Set> autoRegisteredConverterFactories; @Autowired private ConverterRegistry converterRegistry; @PostConstruct public void conversionService() { if (autoRegisteredConverters != null) { for (Converter converter : autoRegisteredConverters) { converterRegistry.addConverter(converter); } } if (autoRegisteredConverterFactories != null) { for (ConverterFactory converterFactory : autoRegisteredConverterFactories) { converterRegistry.addConverterFactory(converterFactory); } } } } 

然后注释您的转换器:

 @SuppressWarnings("rawtypes") @TypeConverter public class StringToEnumConverterFactory implements ConverterFactory { @SuppressWarnings("unchecked") public  Converter getConverter(Class targetType) { return new StringToEnum(targetType); } private final class StringToEnum implements Converter { private Class enumType; public StringToEnum(Class enumType) { this.enumType = enumType; } @SuppressWarnings("unchecked") public T convert(String source) { return (T) Enum.valueOf(this.enumType, source.trim().toUpperCase()); } } } 

尝试这个:

 @SpringBootApplication public class Application extends SpringBootServletInitializer { @Bean public AssessmentService assessmentService(){ return new AssessmentService(); } @Bean public StringToAssessmentConverter stringToAssessmentConverter(){ return new StringToAssessmentConverter(assessmentService()); } @Bean(name="conversionService") public ConversionService getConversionService() { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); Set converters = new HashSet(); //add the converter converters.add(stringToAssessmentConverter()); bean.setConverters(converters); return bean.getObject(); } // separate these class into its own java file if necessary // Assesment service class AssessmentService {} //converter class StringToAssessmentConverter implements Converter { 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; } } } } 

或者如果你的StringToAssessmentConverter已经是一个spring bean:

 @Autowired @Bean(name="conversionService") public ConversionService getConversionService(StringToAssessmentConverter stringToAssessmentConverter) { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); Set converters = new HashSet(); //add the converter converters.add(stringToAssessmentConverter); bean.setConverters(converters); return bean.getObject(); }