我正在使用带有 Java 编程配置的 Spring Boot。我正在使用 Spring 的 ConversionService 和 Spring 的 Converter 接口(interface)的几个自定义实现。我想在配置时用我的 ConversionService bean 注册所有转换器。要注意的是,其中一些转换器有自己的注释配置的依赖项,并且这些没有被连接。例如配置类如下:
@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 通过配置类将每个 Converter 实现添加到它,但转换器实现中的 Autowiring 字段都没有被填充。它们为空。
我目前的解决方案如下:
@Component
public class ConverterImpl implements Converter
{
@Lazy
@Autowired
private DependentClass myDependency;
//The rest of the implementation
}
简而言之,转换器实现中的所有 Autowiring 字段也被注释为“惰性”。这似乎有效,因为字段在首次访问时会被填充。不过,这感觉像是一个 hack。我的问题是:有没有更好的方法来实现我想要的?我在 Spring 文档中遗漏了什么吗?整体方法是否存在缺陷?
最佳答案
我不认为这是一个 hack,但不能保证它总是有效。唯一的其他方法是在单独的 ApplicationContext
中创建您的 Converters
,例如父上下文。请记住,ConversionService
将用于在注入(inject)它们之前创建 bean 定义和转换依赖项,因此它必须在创建任何其他 bean 之前可用(因此您的空依赖项问题)。
关于java - 具有空的 Autowiring 依赖项的 Spring Boot JavaConfig,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26315635/