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

How to automatically add all Converters to a FormatterRegistry in Spring?

我有一个 Spring Boot 2.1.6 项目,它经常使用 Spring 的 Converter(其中 24 个)。全部标注为@Component。现在我添加了一个 @EnableWebMvc 并且必须通过 registry.addConverterWebMvcConfigurer.addFormatters

中将它们添加到 FormatterRegistry

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

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);
    }
}

因为你已经实现了Converter接口并且还用@Component注解了它们,你可以通过将它们作为一个集合注入来获得它们。 @Autowired List<Converter> converters;