1. Introducción
Aunque JDK8 es muy bueno, la versión de JDK se lanzó a JDK20, y la versión posterior a JDK8 se actualizó con muchas características nuevas, como modularización, ZGC, subprocesos virtuales, concurrencia estructural, etc., que también son muy atractivas, por lo que Decidí usar Proyectos basados en JDK8 actualizados a la última versión de LTS, JDK17.
2 Registro del proceso de actualización
2.1 Instalar JDK17
Descarga la última versión de JDK17 jdk-17_linux-x64_bin.tar.gz
, descomprímelo y muévelo al /usr/lib/jvm/
directorio
$ sudo su -
# tar -xzf jdk-17_linux-x64_bin.tar.gz
# mv jdk-17.0.2 /usr/lib/jvm/java-17
复制代码
Luego modifique ~/.bashrc
y configure la variable de entorno relacionada con Java en JDK17
# vim ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-17
export JRE_HOME=${JAVA_HOME}/jre
export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib
export PATH=${JAVA_HOME}/bin:$PATH
复制代码
Después de que la variable de entorno surta efecto, verifique que la versión actual de jdk sea JDK17
# source ~/.bashrc
# java -version
openjdk version "17.0.2" 2022-01-18
OpenJDK Runtime Environment (build 17.0.2+8-86)
OpenJDK 64-Bit Server VM (build 17.0.2+8-86, mixed mode, sharing)
复制代码
2.2 Actualizar la versión de primavera y compilar
Modifique el pom.xml
archivo del proyecto, cambie la versión Spring Boot y Spring Cloud por
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<spring-cloud.version>Greenwich.SR3</spring-cloud.version>
</properties>
复制代码
Modificar a la última versión de lanzamiento oficial:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<spring-cloud.version>2022.0.2</spring-cloud.version>
</properties>
复制代码
Compile el proyecto y reporte el siguiente error:
程序包javax.servlet.http不存在
程序包javax.validation不存在
复制代码
javax
El motivo es que se ha cambiado el nombre del paquete original , reemplazando todos los paquetes dependientes jakarta
en el proyecto conjavax
jakarta
Continúe compilando e informe el siguiente error:
[ERROR] 找不到符号
[ERROR] 符号: 类 EnableEurekaClient
[ERROR] 位置: 程序包 org.springframework.cloud.netflix.eureka
复制代码
La razón es que la nueva versión no tiene @EnableEurekaClient
anotaciones y es reemplazada por@EnableDiscoveryClient
Continúe compilando e informe el siguiente error:
[ERROR] 找不到符号
[ERROR] 符号: 方法 apply()
[ERROR] 位置: 接口 io.github.resilience4j.core.functions.CheckedSupplier<java.lang.Object>
复制代码
La razón es resilience4j
que CheckedSupplier
la nueva versión de la interfaz no tiene apply()
método, así que cámbielo a get()
método
Continúe compilando e informe el siguiente error:
[ERROR] 对于RetryableException(int,java.lang.String,feign.Request.HttpMethod,java.util.Date), 找不到合适的构造器
[ERROR] 构造器 feign.RetryableException.RetryableException(int,java.lang.String,feign.Request.HttpMethod,java.lang.Throwable,java.util.Date,feign.Request)不适用
[ERROR] (实际参数列表和形式参数列表长度不同)
[ERROR] 构造器 feign.RetryableException.RetryableException(int,java.lang.String,feign.Request.HttpMethod,java.util.Date,feign.Request)不适用
[ERROR] (实际参数列表和形式参数列表长度不同)
复制代码
El motivo es que el constructor openfeign
de la nueva versión de RetryableException
la clase de excepción ha cambiado y el código anterior se cambia según sea necesario:
@Bean
public ErrorDecoder feignError() {
return (key, response) -> {
if (response.status() >= 500) {
FeignException exception = FeignException.errorStatus(key, response);
return new RetryableException(
response.status(),
exception.getMessage(),
response.request().httpMethod(),
new Date());
}
// 其他异常交给Default去解码处理
return defaultErrorDecoder.decode(key, response);
};
}
复制代码
Cambiar al siguiente código
@Bean
public ErrorDecoder feignError() {
return (key, response) -> {
if (response.status() >= 500) {
FeignException exception = FeignException.errorStatus(key, response);
return new RetryableException(
response.status(),
exception.getMessage(),
response.request().httpMethod(),
new Date(),
response.request());
}
// 其他异常交给Default去解码处理
return defaultErrorDecoder.decode(key, response);
};
}
复制代码
Luego de cambiar para continuar compilando, se reporta el siguiente error:
程序包org.junit不存在
程序包org.junit.runner不存在
程序包junit.framework不存在
复制代码
Esto se debe a que las versiones anteriores usaban las anotaciones junit4
correspondientes junit5
. Muy pronto:
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
@Ignore
@RunWith(MockitoJUnitRunner.class)
public class FileSyncerTest {
@Before
public void setUp() {
}
@Test
public void testCase1() throws Exception {
}
}
复制代码
cambiado a
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
@Disabled
@ExtendWith(MockitoExtension.class)
public class FileSyncerTest {
@BeforeEach
public void setUp() {
}
@Test
public void testCase1() throws Exception {
}
}
复制代码
Continúe compilando después de cambiarlo, y la compilación pasa.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 8.582 s (Wall Clock)
[INFO] Finished at: 2023-05-04T16:39:42+08:00
[INFO] Final Memory: 59M/214M
[INFO] ------------------------------------------------------------------------
复制代码
2.3 Iniciar el proyecto
Inicie el proyecto después de pasar la compilación, pero el inicio falla y se informa el siguiente error:
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @7634b327
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:199)
at java.base/java.lang.reflect.Method.setAccessible(Method.java:193)
at net.sf.cglib.core.ReflectUtils$2.run(ReflectUtils.java:56)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:318)
at net.sf.cglib.core.ReflectUtils.<clinit>(ReflectUtils.java:46)
复制代码
这是因为从JDK9开始支持模块化了,项目中使用的部分组件可能还没有支持模块化,所以需要在jar包启动时添加add-opens
jvm启动参数参数,我是通过在pom文件中添加build参数实现的:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 添加 add-opens jvm参数 -->
<jvmArguments>--add-opens java.base/java.lang=ALL-UNNAMED</jvmArguments>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
复制代码
修改完后重新编译启动,启动仍然失败,报以下错误:
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
Caused by: java.lang.NullPointerException: null
复制代码
这是因为项目中使用了knife4j,由于版本比较低,底层依赖的是spring-fox,支持的是openapi 2.x版本,而spring boot 3.0只支持openapi 3.x版本,所以knife4j版本依赖由:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.5</version>
</dependency>
复制代码
改为:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
复制代码
同时将swagger的相关注解@Api
、@ApiOperation
、@ApiParam
、@ApiModel
、@ApiModelProperty
替换为openapi3
对应的注解:@Tag
、@Operation
、 @Parameter
、 @Schema
、 @SchemaProperty
修改完后,重新编译启动,这次能正常启动了
但是web访问项目接口时报以下错误:
Caused by: java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
at org.springframework.web.cors.CorsConfiguration.validateAllowCredentials(CorsConfiguration.java:516)
at org.springframework.web.servlet.handler.AbstractHandlerMapping.getHandler(AbstractHandlerMapping.java:538)
at org.springframework.web.servlet.DispatcherServlet.getHandler(DispatcherServlet.java:1275)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011)
... 36 common frames omitted
复制代码
这个是跨域的问题,新版本spring MVC的CorsRegistry
已经没有allowedOrigin()
方法了,替换为新接口allowedOriginPatterns()
即可,代码示例如下:
@Configuration
public class WebCorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
复制代码
到此升级完成!