如何在Spring中自动将所有转换器添加到FormatterRegistry?

如何在Spring中自动将所有转换器添加到FormatterRegistry?,spring,spring-boot,converters,Spring,Spring Boot,Converters,我有一个SpringBoot2.1.6项目,它大量使用Spring的Converters(其中24个)。所有组件都标注为@组件。现在我已经添加了一个@EnableWebMvc,并且必须通过webmvcconfiguer.addFormatters中的registry.addConverter将它们添加到FormatterRegistry中 我是否可以让Spring自动查找所有这些文件(它们都在同一个单独的包中)并添加它们,还是每次添加转换器时都必须手动添加所有24个文件并更改我的WebMVCCo

我有一个SpringBoot2.1.6项目,它大量使用Spring的
Converter
s(其中24个)。所有组件都标注为
@组件
。现在我已经添加了一个
@EnableWebMvc
,并且必须通过
webmvcconfiguer.addFormatters中的
registry.addConverter
将它们添加到
FormatterRegistry

我是否可以让Spring自动查找所有这些文件(它们都在同一个单独的包中)并添加它们,还是每次添加转换器时都必须手动添加所有24个文件并更改我的
WebMVCConfiguer

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
List<Formatter> formatters;

    @Override
    public void addFormatters(FormatterRegistry registry) {

        formatters.forEach(registry::addFormatter);
    }
}
导入org.springframework.context.annotation.Configuration; 导入org.springframework.format.Formatter; 导入org.springframework.format.FormatterRegistry; 导入org.springframework.web.servlet.config.annotation.WebMVCConfiguer; 导入org.springframework.web.servlet.config.annotation.WebMVCConfigureAdapter; 导入java.util.List; @配置 公共类WebConfig扩展了WebMVCConfigureAdapter{ @自动连线 列表格式化程序; @凌驾 公共void addFormatters(FormatterRegistry注册表){ forEach(注册表::addFormatter); } }
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.context.annotation.Configuration;
导入org.springframework.format.Formatter;
导入org.springframework.format.FormatterRegistry;
导入org.springframework.web.servlet.config.annotation.WebMVCConfiguer;
导入org.springframework.web.servlet.config.annotation.WebMVCConfigureAdapter;
导入java.util.List;
@配置
公共类WebConfig扩展了WebMVCConfigureAdapter{
@自动连线
列表格式化程序;
@凌驾
公共void addFormatters(FormatterRegistry注册表){
forEach(注册表::addFormatter);
}
}

由于您已经实现了
转换器
接口,并且还使用
@Component
对它们进行了注释,因此您可以通过将它们作为一个集合注入来获取它们<代码>@自动接线列表转换器

因为您已经实现了
转换器
接口,并且还使用
@Component
对它们进行了注释,所以您可以通过将它们作为一个集合注入来获取它们<代码>@自动接线列表转换器

它们都必须实现格式化程序接口,对吗?然后您可以简单地执行@Autowired列表格式化程序@拉凯什:
转换器
,但是是的,这很有帮助。请给我一个答案,这样我就可以投票接受了。或查找此问题的副本。:-)他们都必须实现格式化程序接口,对吗?然后您可以简单地执行@Autowired列表格式化程序@拉凯什:
转换器
,但是是的,这很有帮助。请给我一个答案,这样我就可以投票接受了。或查找此问题的副本。:-)