Springboot2.x upgrade documentation

    Foreword

First, select the corresponding version

Second, the pre-upgrade considerations

Third, modify pom.xml dependence

Four, maven rely upgrade

Fifth, the configuration file upgrade

Modified six code layer

    Reference material


Foreword

As companies need to upgrade existing technology infrastructure, springboot versions will need to upgrade to 2.x above, the corresponding Springcloud version also need to upgrade. The following escalation of the process and make a summary.


First, select the corresponding version

There is Springboot and Springcloud version correspondence, concerning the relevance Springboot and Springcloud version, you can refer to the official link: springboot and springcloud correspondence between the version , the paper Springboot-2.1.9 and version upgrade Springcloud-Greenwich.SR2 demonstration as an example.


Second, the pre-upgrade considerations

Note: springboot-dependent on JDK8 2.x and above, and support for new features of JDK9. So to confirm JDK version of the project.

Note: springboot-2.x for some third-party libraries have been upgraded version, the most important example: Spring Framework 5+ and Tomcat 8.5+. So for the integrated Spring 4 may be discarded in the new version, for example: guava cache


Third, modify pom.xml dependence

Process are shown in springboot development project specifications, for example, the parent project definitions parent, and then introduced in Springcloud dependent manner. pom.xml file modifications divided into the following three steps:

  1. Modify the parent label content, the father of the project engineering is set to springboot-2.x:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/>
    </parent>
    
  2. Content properties tab modify setting values ​​of some basic properties, such as springcloud version:
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>
    
  3. New dependencyManagement label content, new springcloud dependent on:
    <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>
    
  4. You can add the following in pom.xml, settings.xml source without modifying mirror image of Ali warehouse can be used to download a jar.
    <repositories>
        <repository>
            <id>maven-ali</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public//</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
                <updatePolicy>always</updatePolicy>
                <checksumPolicy>fail</checksumPolicy>
            </snapshots>
        </repository>
    </repositories>
    

After waiting jar package is downloaded, the first step in the upgrade has been completed, the next managing a jar.


Four, maven rely upgrade

After the upgrade version, it will lead to a lot of incompatible jar package and configuration files, so now you want to start editing content dependencies and configuration files. Note: IDEA expect developers to start using the upgrade project as a development tool, software screenshots in this article are from the IDEA, IDEA and expect to complete the upgrading of the aid project.

You can see the right side IDEA, Maven view, which version-dependent failure, as shown, the version number is "unknown", i.e. need to be modified to an example eureka, the new version in the artifactId belongs to is eureka change, change to the correct artifactId can be.

If you are using eclipse, then the jar package download process will be given as follows:

  1. eureka-client-artifactId changes:

    1.5.7的版本中,eureka依赖:
    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    
    2.x以上的版本,eureka依赖:
    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>	   
    
  2. eureka-server-artifactId changes:

    1.5.7的版本中,eureka依赖:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
    
    2.x以上的版本,eureka依赖:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    
  3. feign-artifactId changes:

    1.5.7的版本中,feign依赖:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
    </dependency>
    
    2.x以上的版本,feign依赖:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  4. mybatis rely upgrade, the correspondence between mybatis-springboot-stater version of the springboot version, see Resources mybatis-springboot-starter official documents

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.1</version>
    </dependency>
    

After modifying, IDEA's maven-> dependencies view, originally as "unknown" version of the package will appear as the correct version.


Fifth, the configuration file upgrade

Next, modify the configuration file, springboot-2.x abandoned many of its original configuration when you open the configuration file with IDEA, you'll find several configurations appear red wavy line as shown, you can quickly IDEA repair (shortcut Alt + Enter) correction, which is the reason for recommendation to use IDEA again. Or you can be modified according to article summarizes the configuration table, but not necessarily all.
Here Insert Picture Description

  1. web part:

    old property new property remark
    server.context-path server.servlet.context-path Project Access Path
    server.context-parameters.* server.servlet.context-parameters.* ServletContext初始化参数
    spring.http.multipart.maxFileSize spring.servlet.multipart.max-file-size 限定单个文件上传大小的上限
    spring.http.multipart.maxRequestSize spring.servlet.multipart.max-request-size 限定单次请求文件大小的上限
  2. actuator部分:

    old property new property remark
    management.context-path management.server.servlet.context-path actuator暴露接口的前缀
    management.security.enabled actuator是否需要安全保证
    management.port management.server.port actuator暴露的端口
    endpoints.key.enabled management.endpoint.key.enabled 配置指定actuatorEndpoint
    management.endpoints.web.exposure.include=* 暴露所有端点
    endpoints.health.sensitive actuator的health接口是否需要安全保证
  3. security部分:

    old property new property remark
    security.user.name spring.security.user.name username
    security.user.password spring.security.user.password password
    security.basic.path (通过代码配置)
    security.basic.enabled (通过代码配置)
  4. redis部分:

    old property new property remark
    spring.redis.pool.max-active spring.redis.jedis.pool.max-active 最大活动连接数量
    spring.redis.pool.max-wait spring.redis.jedis.pool.max-wait 最大阻塞等待时间
    spring.redis.pool.max-idle spring.redis.jedis.pool.max-idle 最大空闲连接数量
    spring.redis.pool.min-idle spring.redis.jedis.pool.min-idle 最小空闲连接数量
  5. quartz部分:

    old property new property remark
  6. datasource部分:

    old property new property remark
    spring.datasource.driverClassName spring.datasource.driver-class-name
    spring.datasource.url spring.datasource.jdbc-url 多数据源
    spring.datasource.url spring.datasource.url 单数据源

    注意: 在新版本中,MySQL的驱动类名也变了,启动一个带有数据源的项目后,您将在控制台中看到如下日志信息:

    Loading class ‘com.mysql.jdbc.Driver’. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

  7. eureka部分:

    old property new property remark
    spring.cloud.client.ipAddress spring.cloud.client.ip-address eureka客户端的ip地址

六、代码层的修改

类所属的包名的改变
新版本中有一些类的包名更改了,例如DataSourceBuilder类:该类原有的包路径为

// 1.5.7版本中的路径
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
// 2.x版本中的路径
import org.springframework.boot.jdbc.DataSourceBuilder;

对于此类问题有很多,修改起来也比较简单,您可以使用IDEA自动修复工具进行包的改变,您只需要删除错误的import语句,IDEA会为您自动导包。

项目启动报错

接下来将解决一个比较棘手的问题:在本人升级的项目中使用了Spring4.x具有的guava cache,但是该组件在Spring 5中废除,取而代之的是caffeine。这意味着程序将不能再使用guava cache,尝试降低spring-context-support.jar的版本也是不行的。项目启动报错如图:
Here Insert Picture Description对使用guava cache的工程进行代码修改,将缓存策略修改为caffeine。原有的guava缓存策略代码如下:

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的代码如下,配置与使用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;
}

springboot-2.x中redis的相关代码也需要修改,原有的代码如下:

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");
}

升级后的RedisCacheManager删除了这个构造方法,修改代码如下所示,有关redis的最新使用方法请参考官方文档:Spring Data Redis官方文档

public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
    config.entryTtl(Duration.ofMillis(72000));

    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;
}

由devtools引发的类转换异常

在解决了代码编译问题之后,启动项目在运行时发现报错,大致归为ClassCastException: A cannot be cast to A的问题,明明是同一个类,但是在A aa = (A) obj;的时候发生异常。

在百度和查阅文档之后,发现是因为devtools造成的。devtools重新启动功能通过使用两个类加载器来实现,默认情况下,IDE加载的文件以 “restart” classloader加载,而任何以.jar结尾的文件将以“base” classloader加载。本人涂着省事的目的直接禁用了devtools依赖。以下是官方文档的说明已经解决问题的办法,您可以在META-INF/spring-devtools.properties文件中加入一些内容。更多详情参见spring-boot-devtools官方文档
Here Insert Picture Description
前端request请求404

再次启动项目后,发现前端请求后台的接口有很多都是404,进一步发现这些请求都是xxx.do的方式,您可以进行如下配置:spring.mvc.pathmatch.use-suffix-pattern=true,建议新创建的项目不要使用.do或.action结尾的请求。具体原因参考springboot官方文档
Here Insert Picture Description
前端request请求406

再次启动项目后,发现前端请求后台的接口存在部分406,另外在控制台中有Could not find acceptable representation报错。请您修改application启动类代码,继承WebMvcConfigurationSupport,并重新配置消息转化类和新增ResourceHandler,代码如下:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class MmsOperateApplication extends WebMvcConfigurationSupport {
    
    public static void main(String[] args) {
        SpringApplication.run (MmsOperateApplication.class, args);
    }

    @Override
    public 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);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/index.html")
                .addResourceLocations("classpath:static/index.html");
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }
}

在修改完毕后,本人所升级的项目已能够正常启动。关于更多的问题或配置将在以后的日子里进行更新。


参考资料

[. 1] Upgrading the Spring from the Boot for 1.5
[2] springboot springcloud and the corresponding version described
[. 3] Spring-Redis document
[. 4] springcloud document
[. 5] Caffeine official documents
[. 6] MyBatis-springboot-official documents Starter

Released three original articles · won praise 3 · views 96

Guess you like

Origin blog.csdn.net/qq_38756958/article/details/104482085