2017-02-28 41 views
0

我正在努力使用spring引导在转换器类中自动装入依赖关系。什么是最优雅的解决方案来解决这个问题?如何在Spring Boot Converter中自动装入依赖关系?

配置

@Configuration 
public class Config { 

    @Bean 
    public ConversionServiceFactoryBean conversionFacilitator() { 
     ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); 
     factory.setConverters(getConverters()); 
     return factory; 
    } 


    private Set<Converter> getConverters() { 
     Set<Converter> converters = new HashSet<>(); 
     converters.add(new MyConverter()); 
     return converters; 
    } 
} 

转换器类,而不是让Spring创建

@Component 
public class MyConverter implements Converter<Type1, Type2> { 

    @Autowired 
    private Dependency dependency; // Null here due to the component not being injected 


    @Override 
    public Type2 convert(Type1 type1) { 
     return dependency.something(type1); 
    } 
} 
+0

你能告诉你怎么设置'Dependency'弥补DI?我相信这可能是一个问题。 –

回答

1

的依赖性不被注入,因为你与新创建MyConverter。

您不需要一种方法来返回一组转换器。春天可以为你做,只需要自动连线。 Spring非常聪明,可以为您提供一组所有找到的转换器实现。

你应该使用类似:

@Configuration 
public class Config { 

    @Bean 
    @Autowired 
    public ConversionServiceFactoryBean conversionFacilitator(Set<Converter> converters) { 
    ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); 
    factory.setConverters(converters); 
    return factory; 
    } 
} 
+0

谢谢,我没有想到春天是那么聪明。 – Grim

相关问题