springboot版本升级从1.x升级到2.x

博主分享从Spring Boot 1.5.7升级到2.1.9版本的经验。大版本升级使许多组件和配置无法正常使用,需做相应处理,如修改pom依赖、配置文件等。涉及parent、eureka、日志、redis等组件,还提及Web项目中jsp和html升级,以及时间、cas登录等问题。

springboot版本升级遇到的问题和注意

由于近期接到需求把项目全部升级到springboot2.x版本,经过不断的尝试和排错,总结到一些经验,现分享给大家。避免大家采坑。(我是从springboot1.5.7版本升级到springboot2.1.9版本)

由于大版本的升级,许多组件和配置都不能正常使用。所以要适应版本的更改,就要做一些相应的处理。

注意springboot2.x版本的jdk是1.8+,maven版本3.6.1+

不多说直接来!
下面是pom依赖的升级和相关配置文件的更改

Springboot 服务项目

1.Springboot版本升级相对应的parent

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.9.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

相对应的项目访问路径content-path也有更改
server.context-path变成server.servlet.context-path

2.eureka

springboot1.5.7版本对应的pom依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>

springboot2.1.9版本对应的pom依赖

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka.instance.preferIpAddress=true
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}
eureka.client.serviceUrl.defaultZone=http://部署的eureka ip:端口/eureka/

3.日志处理

springboot2.x版本有对日志进行集成,所以不需要引用太多的pom依赖对日志进行处理

<dependency> <!-- 引入log4j2依赖 -->
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
		<dependency><!-- 异步日志支持 -->
			<groupId>com.lmax</groupId>
			<artifactId>disruptor</artifactId>
			<version>3.3.6</version>
		</dependency>

4.config

这里我连接的是配置中心。

<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.serviceId=api-config-server
spring.cloud.config.profile=test
spring.cloud.config.enabled=true

5.actuator

如果想对您的项目进行监控可以加上actuator依赖,可以通过访问你设置的监控地址对您的项目进行监控

       <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

management.server.port=8081
management.endpoint.shutdown.enabled=true
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*

**注意,此配置只能放在bootstrap.properties。放入其他的配置文件中项目在启动的时候会扫描不到,以至于将不能监控您的项目。 **

6.security

security是一个神奇的存在,大家想了解它的具体功能可以去查官方文档。(慎用!!!!!)
由于升级的项目中存在cas登录,所以加上security依赖之后会存在跳不过去的情况。因为加上security依赖之后,会先对security进行验证,而原来在springboot1.5.7版本中在配置文件中配置的security账号和密码会全部失效。由于时间比较紧,新的配置还没有研究,有相关经验的小伙伴或者有好的解决办法可以进行交流。

<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

失效配置:

#security.user.name=123
#security.user.password=123

7.redis

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
				<exclusion>
					<groupId>io.lettuce</groupId>
					<artifactId>lettuce-core</artifactId>
				</exclusion>
			</exclusions>
</dependency>
<dependency>
		    <groupId>redis.clients</groupId>
		    <artifactId>jedis</artifactId>
</dependency>

由于我采用的是jedis连接,所以把lettuce排除掉了,引入jedis依赖。

spring.redis.jedis.pool.max-active=100
spring.redis.jedis.pool.max-idle=100
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.min-idle=100

还有代码级别的改动:
RedisCacheManager配置。下面给了两种方式:

public RedisCacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
    //过期时间单位毫秒
    redisCacheManager.setDefaultExpiration(72000);
    redisCacheManager.setUsePrefix(true);
    redisCacheManager.setCachePrefix(new DefaultRedisCachePrefix());
    ArrayList<String> cacheNames = new ArrayList<>();
    cacheNames.add("common-cache-redis-caching");
}
--------------------------------------------------------
public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        config.entryTtl(Duration.ofMillis(72000));
        config.computePrefixWith(cacheName -> appName.concat(":").concat(cacheName).concat(":")); 
        Set<String> cacheNames = new HashSet<>();
        cacheNames.add("common-cache-redis-caching");

        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put("common-cache-redis-caching", config);

        RedisCacheManager cacheManager = RedisCacheManager.builder(redisTemplate.getConnectionFactory())
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }

8.mysql

由于版本的升级,sql的连接也有了相应的改动。

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mysql?characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=123456
spring.datasource.password=123456
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

连接驱动由原来的com.mysql.jdbc.Driver更改为com.mysql.cj.jdbc.Driver。在这里建议大家配置时区,这样会减少因为时区不一致,而导致的时间相差8小时serverTimezone=Asia/Shanghai

9.guava

由于项目升级到2.x版本,也就是说Spring升级到了5.+的版本.那么Spring4.+版本的guava cache已经失效,需要换成对应的5.+版本.Spingboot1.x 对应的guava的pom依赖和相应的代码都有相应的变动

Springboot1.x:

public GuavaCacheManager guavaCacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    //规定了缓存在1小时没有使用的情况下进行回收
    //规定了缓存的最大容量
    cacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterWrite(1, TimeUnit.HOURS).maximumSize(100000));
    ArrayList<String> cacheNames = new ArrayList<>();
    cacheNames.add("common-cache-guava-caching");
    cacheManager.setCacheNames(cacheNames);

    return cacheManager;
}

在使用springboot-caffeine前,需要导包,pom.xml依赖如下:

<!--原有的spring-boot-starter-cache依赖不变-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--新增caffeine依赖-->
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
</dependency>

使用springboot-caffeine的代码如下,配置与使用guava cache是等同的。有关于caffeine更多的配置或详细信息,请参考caffeine官方文档

public CaffeineCacheManager guavaCacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();
    Caffeine caffeine = Caffeine.newBuilder()
        .initialCapacity(100)
        .maximumSize(100000)
        .expireAfterWrite(1, TimeUnit.HOURS);
    cacheManager.setCaffeine(caffeine);
    ArrayList<String> cacheNames = new ArrayList<>();
    cacheNames.add("common-cache-guava-caching");
    cacheManager.setCacheNames(cacheNames);
    return cacheManager;
}

!!!!上述这些配置服务升级基本全部搞定,但你会发现在启动的时候会报错。那么在bootstrap.propertits中加入一行配置,你的项目就会正常启动

spring.main.allow-bean-definition-overriding=true

想了解具体的原因为什么要加入此配置

10.时间问题

所有项目的升级可能会导致时间的问题,比如返回的时间变成了时区格式返回时间
如果是Web项目,那么请前端的同学修改一下返回格式,如果是后台服务返回不做展示的话想变成dateTime格式只需要编写如下代码。

 public void timeHadle(List<Object> list, Map<String,Object> map) throws ParseException {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
		if (list == null || list.isEmpty()){
			return;
		}
		for(Object obj : list) {
			map = (Map<String, Object>) obj;
			if(map.get("sendTime") != null){
				String sendTime = map.get("sendTime").toString();
				Date parseSendTime = simpleDateFormat1.parse(sendTime);
				String formatSendTime = simpleDateFormat.format(parseSendTime);
				map.put("sendTime", formatSendTime);
			}
			obj = map;
		}
	}

ok。java服务的升级已经全部完成,接下来就到了头疼的Web项目。

还存在的问题就是时间相差8小时,最开始认为是时区问题导致的,但通过排查发现,导致时差相差8小时的原因是因为springboot1.x 和springboot2.x的序列化不同

解决办法添加如下配置:

spring.jackson.time-zone=GMT+8

具体的原因请参考:Springboot-2.x升级后导致时间少8小时

Springboot Web项目

如果你要升级的是一个web项目,那么恭喜你,上面的那些配置只是冰山一角。接下来的东西,会让你痛不欲生。。。

升级一个web项目存在N个坑,会遇到各种各样的问题。
在这里介绍的也是从Springboot1.5.7 升级到Springboot2.1.9 web项目。

1.jsp

Springboot2.x版本对jsp很不友好,需要引入外部依赖。

<!--引入springboot 内嵌tomcat对jsp的解析包-->
<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--servlet依赖jar-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
</dependency>

<!--jsp依赖jar-->
<dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>javax.servlet.jsp-api</artifactId>
   <version>2.3.1</version>
</dependency>

<!--Jstl标签依赖的jar包start-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
</dependency>

注意:所有的jsp文件都要放到webapp下,否则会加载不到相应的文件
ps:如何创建webapp文件夹,请自行搜索!

在Web项目升级的时候,启动类原来继承的SpringBootServletInitializer会导致406的问题。406是json序列化的问题,可百度自行搜索。所以在升级之后,我选择继承WebMvcConfigurationSupport

继承WebMvcConfigurationSupport的时候web项目会404而无法跳转相应的jsp页面,但你会发现直接访问静态页面的时候是可以的。所以那一定是跳转存在问题。通过查看官方文档发现当启动类在继承WebMvcConfigurationSupport的时候,这个类存在的默认配置会自动帮你屏蔽掉你配置的加载的jsp页面,那么就需要重写

那么在继承WebMvcConfigurationSupport的时候需要重写json序列化。

我采用的是fastjson序列化,相关代码如下。

 @Override
	protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		 //1、定义一个convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2、添加fastjson的配置信息
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //3、在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //4、将convert添加到converters中
        converters.add(fastConverter);
        //5、追加默认转换器
        super.addDefaultHttpMessageConverters(converters);
	}

最近遇到的新坑:
由于Springboot2.x继承WebMvcConfigurationSupport,json序列化发生了改变,返回值为null的时候是默认不展示的。以至于我的后台一直在报404,但看接口是undefined。
所以在重写json序列化的时候,要注意返回的形式.
还是以fastjson为例,需要在序列化的时候添加SerializerFeature.WriteNullStringAsEmpty就可以解决.

fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty);

对自定义的json树组要是以String返回的,要改成Object,否则返回的报文都是以字符串的方式进行返回,无法解析。

还有一点升级版本后的Web项目,对返回的xml格式的报文,也有影响,通过后台发现返回的xml报文,都变成了字符串无法解析。
所以要变成Object返回,不要以String形式返回。并设置消息头。(这个配置只针对xml形式)

 response.setHeader("Content-Type","text/xml;charset=UTF-8");
                response.setContentType("text/xml;charset=UTF-8");
                try (PrintWriter writer = response.getWriter();){
                    writer.println(mmdata.getMmdl());
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
                //return getXmlSuccessResponse(mmdata.getMmdl());
       //注意注释掉的代码,不要转换其他形式返回

2.HTML

上面介绍了jsp的升级方式,那么现在来说说html方式的升级。html方式的升级就比jsp要简单的多。html文件放在resource/static下即可.

结尾!

如果有引用cas登录,那么修改的时候,要注意cas的改变。由于我所升级的项目都部署了docker,一定要注意cas的跳转地址!!!要注意跨域的问题。

由于我的Web项目放在k8s下部署,所以访问规则是路由规则。导致我项目的访问路径会少命名空间路径,这里我采用的是把前端文件写死加上命名空间路径,大家有什么好的想法和建议能解决在k8s上获取路径的问题,感激不尽!

欢迎转载!!!

<think>我们正在处理用户关于SpringBoot2.3.x升级2.7.x的问题。根据用户提供的引用信息,我们可以整合一些关键点,特别是引用[1]和引用[3]中提到的关于版本更新和依赖管理的部分。注意:引用[2]提到了Kafka客户端版本兼容性问题,引用[4]是关于NetBackup升级的,与SpringBoot升级关系不大,但我们可以忽略不相关引用。升级SpringBoot版本是一个多步骤的过程,需要谨慎操作。根据SpringBoot官方升级指南,我们可以总结以下步骤:1.**更新SpringBoot版本号**:在Maven或Gradle中修改父项目或插件的版本号。2.**处理依赖库的兼容性**:检查并更新相关依赖库的版本,确保与SpringBoot2.7.x兼容。3.**配置更新**:根据版本变更日志调整配置文件(如application.properties/yml)。4.**代码更新**:修改因API变化而受影响的代码。5.**测试**:全面测试应用程序。我们参考引用[1]中提到的在pom.xml中更新版本号的方式,以及引用[3]中关于Logback升级的注意事项(因为SpringBoot2.7.x可能使用更新的Logback版本)。具体步骤:**步骤1:更新SpringBoot版本**对于Maven项目,在pom.xml中修改父项目的版本:```xml<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.18</version><!--使用2.7.x的最新版本,这里以2.7.18为例--></parent>```对于Gradle项目,在build.gradle中修改插件版本:```groovyplugins{id'org.springframework.boot'version'2.7.18'}```**步骤2:更新依赖库**检查所有依赖库是否与SpringBoot2.7.x兼容。特别是注意:-数据库驱动-各种SpringBootStarters-第三方库(如Kafka、Logback等)引用[3]提到Logback从1.2.x升级1.3.x的注意事项,因为SpringBoot2.7.x可能使用Logback1.3.x。需要检查日志配置文件(logback.xml)是否符合新版本要求。引用[2]提醒我们,如果使用Kafka,需要注意客户端版本兼容性。SpringBoot2.7.x默认使用的Kafka客户端版本是2.8.x,如果需要使用2.4.0客户端,可能需要覆盖版本(但建议使用SpringBoot管理的版本)。**步骤3:处理配置变更**查阅SpringBoot2.4到2.7的官方迁移指南,特别注意配置属性的变化。例如:-在2.4版本中,配置文件处理机制有重大变化(多文档配置文件支持,默认激活的配置文件改变等)。-一些过时的属性被移除,需要替换为新的属性。官方迁移指南链接:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.4-Release-Notes以及后续版本的ReleaseNotes。**步骤4:代码更新**检查并更新代码中过时的API。例如:-在SpringBoot2.3中,`server.max-http-header-size`被替换为`server.max-http-request-header-size`和`server.max-http-response-header-size`。-SpringBoot2.4开始,`spring.main.allow-bean-definition-overriding`的默认值从true变为false,如果项目中有同名bean覆盖,需要显式设置为true或解决冲突。**步骤5:测试**进行全面的测试,包括单元测试、集成测试和功能测试。另外,建议逐步升级:先从2.3.x升级2.4.x,再升级2.5.x,然后2.6.x,最后2.7.x。每一步都解决兼容性问题,这样更容易定位问题。根据引用[3]的提示,在升级过程中要特别注意日志框架的兼容性。Logback1.3.x移除了`StaticLoggerBinder`,因此如果项目中有直接引用该类的代码,需要移除。生成相关问题:1.升级SpringBoot时如何处理依赖库的兼容性问题?2.SpringBoot2.4版本在配置文件处理上有哪些重大变化?3.如何解决SpringBoot升级后出现的日志配置问题?</think>### Spring Boot2.3.x 升级2.7.x 指南 #### 1. **版本更新** 首先修改构建工具的版本声明: - **Maven** (参考引用[1]) ```xml <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.18</version> <!-- 2.7.x最新稳定版 --> </parent> ``` - **Gradle** ```gradle plugins { id 'org.springframework.boot' version '2.7.18' } ``` #### 2. **依赖兼容性检查** - **关键依赖升级**: ```xml <!-- 示例:Spring Cloud 需匹配 2.7.x --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.8</version> <!-- 对应 Boot 2.7.x --> </dependency> ``` - **第三方库适配** (参考引用[2]): - 如使用 Kafka,需确认 `kafka-clients` 版本与 Spring Kafka 兼容 - 使用 `mvn dependency:tree` 检查冲突依赖 #### 3. **配置迁移** - **废弃属性处理**: - 替换 `management.metrics.export.*` 为 `management.*.metrics.export.*` - 移除 `spring.security.oauth2.client.registration.*.client-authentication-method` - **配置文件调整**: ```yaml # 新版本多文档配置语法 (YAML) spring: config: activate: on-profile: prod --- spring: profiles: dev ``` #### 4. **日志框架升级** (参考引用[3]) Logback 1.3.x 需注意: - 移除 `StaticLoggerBinder` 引用 - 配置文件更新: ```xml <!-- logback.xml 示例 --> <configuration> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{ISO8601} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="INFO"> <appender-ref ref="CONSOLE" /> </root> </configuration> ``` #### 5. **代码变更** - 过时 API 替换: - `SpringApplication.run()` 无需显式调用 `setAllowBeanDefinitionOverriding` - 迁移 `JUnit 4` 到 `JUnit 5` 测试 - 安全配置更新: ```java // 新版本安全配置示例 @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(auth -> auth.anyRequest().authenticated()) .oauth2Login(withDefaults()); } } ``` #### 6. **升级后验证** 1. 运行测试套件:`mvn test` 或 `gradle test` 2. 检查启动日志中的弃用警告 3. 关键功能回归测试 4. 监控内存和性能指标 > **重要提示**:建议通过中间版本逐步升级(如 2.3 → 2.4 → 2.5 → 2.6 → 2.7),每个版本参考官方迁移指南: > - [Spring Boot 2.4 Release Notes](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.4-Release-Notes) > - [Spring Boot 2.7 Migration Guide](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7-Release-Notes)
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值