SpringBoot1.0和2.0中WebMvcConfig的区别
问题背景
从SpringBoot1.0升级到2.0,或者日常搜索别人的代码,发现有些还是1.0的模式,那么如何升级为2.0呢?
问题分析
在springboot1.0中,是extends WebMvcConfigurerAdapter类,大家知道java是多实现单继承的,如果这样做那就只能继承一个,虽然功能无差,但是拓展性就不行了。
在springboot2.0中,对这个配置文件进行了升级,只需要implement WebMvcConfigurer 这个接口就可以了。
WebMvcConfigurer包含了如下方法,可以选择性的实现即可
public interface WebMvcConfigurer {
default void configurePathMatch(PathMatchConfigurer configurer) {
}
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
default void addFormatters(FormatterRegistry registry) {
}
default void addInterceptors(InterceptorRegistry registry) {
}
default void addResourceHandlers(ResourceHandlerRegistry registry) {
}
default void addCorsMappings(CorsRegistry registry) {
}
default void addViewControllers(ViewControllerRegistry registry) {
}
default void configureViewResolvers(ViewResolverRegistry registry) {
}
default void addArgumentResolvers(List resolvers) {
}
default void addReturnValueHandlers(List handlers) {
}
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}
default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
}
default void configureHandlerExceptionResolvers(List resolvers) {
}
default void extendHandlerExceptionResolvers(List resolvers) {
}
@Nullable
default Validator getValidator() {
return null;
}
@Nullable
default MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
以下是springboot2的config代码
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebAdapter for springboot2.0
* @author zhengkai.blog.csdn.net
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers( ViewControllerRegistry registry ) {
registry.addViewController( "/" ).setViewName( "forward:/login.shtml" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
}
}
以下是springboot1的config代码
/**
* WebAdapter for springboot1.0
* @author zhengkai.blog.csdn.net
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Override
public void addViewControllers( ViewControllerRegistry registry ) {
registry.addViewController( "/" ).setViewName( "forward:/login.shtml" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
super.addViewControllers( registry );
}
}
上一篇: SpringBoot中1.0、2.0中自定义缓存的区别
下一篇: shell 命令 find