本文共 2933 字,大约阅读时间需要 9 分钟。
这篇文章记录一下Spring Boot 1.5.22升级至2.x的一些编译问题和对应方法。
文章目录
POM修正
将之前的版本由1.5.22升至2.0.0,然后升至2.1.0、2.2.0、2.3.0、2.3.3,结果证明编译期间产生的问题不多,从2.0.0到2.3.3更少,一般都是由于包的位置改变或者功能过期废弃产生的问题。
org.springframework.boot spring-boot-starter-parent 2.0.0.RELEASE
问题与对应
Relaxed Binding
现象
Relaxed Binding在Spring Boot 2中发生了变化,开发者有可能会碰到如下类似的错误,是在编译阶段就会报错的地方。
package org.springframework.boot.bind does not existcannot find symbol[ERROR] symbol: class RelaxedPropertyResolver
原因
原因是已经内置了Relaxed Binding,但是如果对于业务不熟悉,也可以使用如下方式进行替换:
对应方法
- 修改前代码示例
import部分:import org.springframework.boot.bind.RelaxedPropertyResolver;定义与设定部分:private RelaxedPropertyResolver propertyResolver;
- 修改后代码示例
import部分:
import java.util.Properties;import org.springframework.boot.context.properties.bind.BindResult;import org.springframework.boot.context.properties.bind.Binder;import org.springframework.boot.context.properties.source.ConfigurationPropertySource;import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
定义部分:
private Properties propertyResolver;
设定部分:
Iterablesources = ConfigurationPropertySources.get(env); Binder binder = new Binder(sources); BindResult bindResult = binder.bind("spring.datasource", Properties.class); this.propertyResolver= bindResult.get();
SpringBootServletInitializer
现象
SpringBootServletInitializer在Spring Boot 2的位置又发生了变化,开发者有可能会碰到如下类似的错误,是在编译阶段就会报错的地方。
package org.springframework.boot.bind does not existcannot find symbol[ERROR] symbol: class RelaxedPropertyResolver
原因
在Spring Boot 1.5 中,org.springframework.boot.context.web.SpringBootServletInitializer就deprecated,转移至org.springframework.boot.web.support.SpringBootServletInitializer,而在Spring Boot 2.0中
对应方法
需要使用org.springframework.boot.web.servlet.support.SpringBootServletInitializer。
- 修改前代码示例
import org.springframework.boot.web.support.SpringBootServletInitializer;
- 修改后代码示例
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
JSONException
现象
- 现象: unreported exception org.json.JSONException; must be caught or declared to be thrown
原因
JSONObject的使用中会扔出JSONException
对应方法
用try…catch包裹起来
- 修改前代码示例
JSONObject jsonObject = new JSONObject(param.get()); boolean isBuilding = jsonObject.getBoolean("building");
- 修改后代码示例
boolean isBuilding = false; try { jsonObject = new JSONObject(param.get()); isBuilding = jsonObject.getBoolean("building"); } catch (JSONException e) { e.printStackTrace(); }
javax.validation
现象
- 现象: 提示大量 package javax.validation does not exist以及其他的错误信息
原因
似乎2.3.0中搞丢了?详细参看:
对应方法
手动在Dependency中添加如下最后一版的javax.validation 即可
- pom中添加内容
javax.validation validation-api 2.0.1.Final
总结
这篇文章记录了几个升级至2.x常见的编译问题,相对来说编译问题还是非常容易定位的,参考文档中也列出了Spring Boot 2.0官方给的升级指南,建议参看一下。
参考文档
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide
转载地址:https://liumiaocn.blog.csdn.net/article/details/108396587 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!