如何从自己的自动配置中使用 WebMvcConfigurationSupport

How to use WebMvcConfigurationSupport from own auto-configuration

我想通过 FormattingConversionService 添加 Converters,这需要 @Configuration class 扩展 WebMvcConfigurationSupport:

@Configuration
public class WebAutoConfig extends WebMvcConfigurationSupport {

    @Override
    public FormattingConversionService mvcConversionService() {

        FormattingConversionService fcs = super.mvcConversionService();

        // add Enum converter in order to accept enums
        // case insensitively over Rest:
        fcs.addConverter(
                String.class,
                MyEnum.class,
                new EnumCaseInsensitiveConverter<>( MyEnum.class )
        );

        return fcs;
    }
}

当直接从项目中使用@Configuration 时,它工作得很好,但需要将此逻辑添加到我们自己的 boot-starter,因此不需要在整个项目中重复代码。

问题是,当这个@Configuration 被迁移到启动项目时,

如何解决这个问题?注意使用 WebMvcConfigurationSupport 不是硬性要求。从代码摘录中可以看出,最终目标是将某些枚举配置为由其余控制器不区分大小写地接受。

Edit: 需要补充的是auto-config项目设置正确,其他@Configuration class在同一个包中WebAutoConfig.java 正在执行。认为这个问题与配置 classes 扩展 WebMvcConfigurationSupport(或 WebMvcConfigurerAdapter 就此而言)如何从自动配置中处理有关。

Edit2:到目前为止我设法开始工作的唯一方法是从使用项目扩展配置class:

import myautoconfproject.autoconfigure.WebAutoConfiguration;

@Configuration
public class WebConfiguration extends WebAutoConfiguration {
}

但这不再是真正的自动配置。

为了让包含您的项目作为依赖项的项目自动获取您的配置,您需要将文件 META-INF/spring.factories 添加到您的类路径(在 WebAutoConfig 所在的项目中并且添加行

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
your.package.WebAutoConfig

显然我对 WebMvcConfigurerAdapter 的看法是错误的 - 自动配置选择了一个:

@Configuration
public class WebAutoConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addFormatters( final FormatterRegistry registry ) {

        registry.addConverter(
                String.class,
                MyEnum.class,
                new EnumCaseInsensitiveConverter<>( MyEnum.class )
        );
    }
}