Search code examples
javaspringspring-bootspring-webspring-boot-starter

How to use WebMvcConfigurationSupport from own auto-configuration


I'd like to add Converters via FormattingConversionService, which requires having a @Configuration class extending 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;
    }
}

It works just fine when the @Configuration is used directly from the project, but there's requirement to add this logic to our own boot-starter so there would be no need to duplicate code all over the projects.

Problem is, when this @Configuration is migrated to a starter project, then

  • mvcConversionService() is not executed, and
  • RestControllers routing is broken (ie no requests are mapped correctly).

How to approach this? Note using WebMvcConfigurationSupport is not a hard requirement. As seen from the code excerpt, end goal is to configure certain enums to be accepted case-insensitively by the rest controllers.

Edit: it should be added that the auto-config project is correctly set up, as other @Configuration classes in the same package as WebAutoConfig.java are executing. Think the issue has to do with how configuration classes extending WebMvcConfigurationSupport (or WebMvcConfigurerAdapter for that matter) are being handled from auto-configs.

Edit2: only way I've managed to get to work so far is extending the config class from the using project:

import myautoconfproject.autoconfigure.WebAutoConfiguration;

@Configuration
public class WebConfiguration extends WebAutoConfiguration {
}

But that's not really auto-configuration anymore.


Solution

  • Apparently I was wrong about the WebMvcConfigurerAdapter - that one is picked up by auto-config:

    @Configuration
    public class WebAutoConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addFormatters( final FormatterRegistry registry ) {
    
            registry.addConverter(
                    String.class,
                    MyEnum.class,
                    new EnumCaseInsensitiveConverter<>( MyEnum.class )
            );
        }
    }