1.WebMvcConfigurationAdapter已经废弃,最好用implements WebMvcConfigurer代替:
@Configuration
public class DefaultWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
2.如果使用继承WebMvcConfigurationSupport(使用@EnableWebMvc注解或继承DelegatingWebMvcConfiguration同理),会覆盖application.properties中关于WebMvcAutoConfiguration的设置,需要在自定义配置中实现:
@Configuration
public class DefaultWebMvcConfig extends WebMvcConfigurationSupport {
}
@Configuration
@EnableWebMvc
public class DefaultWebMvcConfig implements WebMvcConfigurer {
}
@Configuration
public class DefaultWebMvcConfig extends DelegatingWebMvcConfiguration {
}
上面代码中需要在类中实现关于WebMvcAutoConfiguration的配置,而不是在application.properties中:
@Configuration
public class DefaultWebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(mappingJackson2HttpMessageConverter);
super.addDefaultHttpMessageConverters(converters);
}
}
总结
implements WebMvcConfigurer : 不会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
@EnableWebMvc + implements WebMvcConfigurer : 会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends WebMvcConfigurationSupport :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends DelegatingWebMvcConfiguration :会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration
class of type WebMvcConfigurer
but without @EnableWebMvc
网友评论