SpringBoot 1.5.x 与 2.x区别

一、依赖jdk及第三库升级

1、jdk版本:2.x 至少需要 JDK 8 的支持,2.x 里面的许多方法应用了 JDK 8 的许多高级新特性。另外,2.x 开始了对 JDK 9 的支持。

2、第三方库:

        1) Spring Framework 5+
        2) Tomcat 8.5+
        3) Flyway 5+
        4) Hibernate 5.2+
        5) Thymeleaf 3+

二、各类报错信息

1、配置文件报错

        现象:如:server.context-path: /spring

        原因:大量的Servlet专属的server.* properties被移到了server.servlet下:

        解决方案:server.context-path: /spring     -->    server.servlet.context-path: /spring

 

2、WebMvcConfigurerAdapter过时

        原因:升级后的springBoot,使用了java8的特性 default 方法,所以直接实现 WebMvcConfigurer 这个接口即可。

        解决方案:由 extends WebMvcConfigurerAdapter 改为 implements WebMvcConfigurer

旧:
public class MvcConfig extends WebMvcConfigurerAdapter 


新:
public class MvcConfig implements WebMvcConfigurer 

 

3、静态资源被拦截

        现象:访问系统的时候css等样式没有加载

        原因:1.5版本时候META-INF/resources / resources / static / public 都是spring boot 认为静态资源应该放置的位置,会自动去寻找静态资源,而在spring boot 2.0则对静态资源也进行了拦截,当拦截器拦截到请求之后,但controller里并没有对应的请求时,该请求会被当成是对静态资源的请求。此时的handler就是 ResourceHttpRequestHandler,就会抛出上述错误。

        解决方案:在拦截器那里排除静态资源的请求路径(assets是放静态资源的路径)

/**  
* 拦截器 
* @param registry 
*/ 
@Override 
public void addInterceptors(InterceptorRegistry registry) { 

    // addPathPatterns 用于添加拦截规则 
    // excludePathPatterns 用户排除拦截 
    registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatternss("/toLogin","/login","/assets/**","/js/**");
}

 

4、全局异常特殊处理 找不到对应的类

原因:新版本后此方法去掉了,需要换成新的方法处理

解决方案:

//旧代码
@Configuration
public class ContainerConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer(){
        return new EmbeddedServletContainerCustomizer(){
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
                container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
                }
            };
        }
    }


//新代码
@Configuration
public class ContainerConfig implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        ErrorPage[] errorPages = new ErrorPage[2];
        errorPages[0] = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        errorPages[1] = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        registry.addErrorPages(errorPages);
    }
}

三、参考文献

http://tengj.top/2018/07/23/springboot2to1/

你可能感兴趣的:(springboot)