2014-10-11 94 views
2

我正在使用Java编程配置的Spring Boot。我使用Spring的ConversionService和Spring的Converter界面的几个自定义实现。我想在配置时使用我的ConversionService bean注册所有转换器。值得注意的是,其中一些转换器具有自己的注释配置依赖关系,并且这些转换器没有连接。例如配置类是类似以下内容:弹簧引导JavaConfig与空的自动装配依赖关系

@Configuration 
public class MyConfig extends WebMvcConfigurerAdapter 
{ 
    @Bean 
    public ConversionService conversionService(List<Converter> converters) 
    { 
     DefaultConversionService conversionService = DefaultConversionService(); 
     for (Converter converter: converters) 
     { 
      conversionService.addConverter(converter); 
     } 
     return conversionService; 
    } 
} 

和部分转换器实现的可能如下:

@Component 
public class ConverterImpl implements Converter 
{ 
    @Autowired 
    private DependentClass myDependency; 

    //The rest of the implementation 
} 

虽然conversionService是有每一个转换器实现通过配置加入到它类中,没有任何转换器实现中的自动装配字段正在填充。它们是空的。

我当前的解决方案如下:

@Component 
public class ConverterImpl implements Converter 
{ 
    @Lazy 
    @Autowired 
    private DependentClass myDependency; 

    //The rest of the implementation 
} 

总之,在该转换器的实现的所有自动装配字段也标注为“懒惰”。这似乎是在第一次访问字段时填充的。这感觉像是一个黑客。我的问题是:有没有更好的方法来实现我想要的?我在Spring文档中丢失了什么?总体方法是否有缺陷?

回答

1

我不认为这是一个黑客,但它并不保证总是工作。这样做的唯一方法是在单独的ApplicationContext中创建您的Converters,例如,父上下文。请记住,ConversionService将用于创建bean定义并在注入它们之前转换依赖项,因此它必须在创建任何其他bean之前可用(因此您的空依赖关系问题)。