Spring Boot 2.0 迁移指南(1.5升级2.0版本特性变化)

Spring Boot 2.0 迁移指南

此文根据springboot在GitHub上的Spring Boot 2.0 迁移指南文章,做出中文解释使其通俗易懂,旨在为自己以及各位了解spring、springboot更多的特性与使用方法。
注意,这不是翻译。

Before You Start

Upgrade to the latest 1.5.x version

Before you start the upgrade, make sure to upgrade to the latest 1.5.x available version. This will make sure that you are building against the most recent dependencies of that line.

官方建议我们先升级到1.5.X版本,运行成功后,再升级2.0,减小升级版本的差异,提升稳定性。

Review dependencies

The move to Spring Boot 2 will upgrade a number of dependencies and might require work on your end. You can review dependency management for 1.5.x with dependency management for 2.0.x to asses how your project is affected.
You may also use dependencies that are not managed by Spring Boot (e.g. Spring Cloud). As your project defines an explicit version for those, you need first to identify the compatible version before upgrading.

大版本升级,很多组件依赖也会随之升级,需要评估好这些组件间接升级的影响。不过也可以自己引入其他包含自己指定版本组件的依赖,把springboot2.0里的排除掉。

Review custom configuration

Any user-configuration that your project defines might need to be reviewed on upgrade. If this can be replaced by use of standard auto-configuration, do it so before upgrading.

检查自定义的Config配置会不会受影响,如果可以使用springboot的自动配置能力,就别自定义了,浪费时间还增加springboot版本升级成本。

Review system requirements

Spring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported. It also requires Spring Framework 5.0.

springboot2.0开始只支持java8及以后版本,spring依赖升级到5.0。

Upgrade to Spring Boot 2

Once you have reviewed the state of your project and its dependencies, upgrade to the latest maintenance release of Spring Boot 2.0. In particular, do not upgrade to Spring Boot 2.0.0.RELEASE as a number of issues have been reported and fixed.
We also recommend to upgrade in phases and not in one jump to the latest GA: first upgrade to 2.0, then 2.1, etc.

做完升级前的检查后,就可以正式升级了,不过不建议升级到2.0.0.RELEASE,一般来说,2.x表示新特性增加,2.0.x表示各类问题修复,不会引入新特性。所以,可以直接升级到比如2.0.9.RELEASE,2.0x最新的版本。
然后,再逐步升级到2.1.x、2.2.x等等。

Configuration properties migration

With Spring Boot 2.0, many configuration properties were renamed/removed and developers need to update their application.properties/application.yml accordingly. To help you with that, Spring Boot ships a new spring-boot-properties-migrator module. Once added as a dependency to your project, this will not only analyze your application’s environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you. This is a must have during your application migration:
Note:Once you’re done with the migration, please make sure to remove this module from your project’s dependencies.


    org.springframework.boot
    spring-boot-properties-migrator
    runtime

升级后会有很多配置属性字段过期或删除,可以引入这个依赖,启动项目后,它会输出可替换的新的配置属性字段。

Building Your Spring Boot Application

Spring Boot Maven plugin

The plugin configuration attributes that are exposed as properties now all start with a spring-boot prefix for consistency and to avoid clashes with other plugins.
For instance, the following command enables the prod profile using the command line:
mvn spring-boot:run -Dspring-boot.run.profiles=prod

一些命令行发生了变化,比如1.x里:

mvn spring-boot:run -Drun.profiles=prod

2.x里,加上了spring-boot前缀:

mvn spring-boot:run -Dspring-boot.run.profiles=prod
Surefire Defaults

Custom include/exclude patterns have been aligned to latest Surefire’s defaults. If you were relying on ours, update your plugin configuration accordingly. They used to be as follows:
Tip:If you are using JUnit 5, you should upgrade Surefire to 2.22.0.


    org.apache.maven.plugins
    maven-surefire-plugin
    
        
             **/*Tests.java
             **/*Test.java
        
        
            **/Abstract*.java
        
    

没看懂啥意思,平时也不怎么用这个插件。反正就是用JUnit 5,surefire 要升级到 2.22.0。

Spring Boot Gradle Plugin

Spring Boot’s Gradle plugin has been largely rewritten to enable a number of significant improvements. You can read more about the plugin’s capabilities in its reference and api documentation.

springboot的gradle插件进行了重写改进。

Dependency Management

Spring Boot’s Gradle plugin no longer automatically applies the dependency management plugin. Instead, Spring Boot’s plugin now reacts to the dependency management plugin being applied by importing the correct version of the spring-boot-dependencies BOM. This gives you more control over how and when dependency management is configured.
For most applications applying the dependency management plugin will be sufficient:
Note:The dependency management plugin remains a transitive dependency of spring-boot-gradle-plugin so there’s no need for it to be listed as a classpath dependency in your buildscript configuration.

apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management' // <-- add this to your build.gradle

没用过gradle,意思应该是 io.spring.dependency-management 插件需要手动添加,而不是自动引入了。

Building Executable Jars and Wars

The bootRepackage task has been replaced with bootJar and bootWar tasks for building executable jars and wars respectively. The jar and war tasks are no longer involved.

老的springboot用gradle打包方式参考https://www.kancloud.cn/george96/java-springboot/613950
2.0里的打包方式参考
Spring Boot Gradle Plugin Reference Guide
即bootRepackage 被替换成了bootJar和bootWar 。

Configuration Updates

The BootRun, BootJar, and BootWar tasks now all use mainClassName as the property to configure the name of the main class. This makes the three Boot-specific tasks consistent with each other, and also aligns them with Gradle’s own application plugin.

mainClassName即启动类 xxxApplication,现在可以作为属性进行配置。

Spring Boot Features

Default Proxying Strategy

Spring Boot now uses CGLIB proxying by default, including for the AOP support. If you need interface-based proxy, you’ll need to set the spring.aop.proxy-target-class to false.

springboot2.0默认使用cglib作为动态代理模式,即使类实现了接口,可以通过配置属性spring.aop.proxy-target-class=false将默认代理切换为jdk。不过spring5.0其实还是默认jdk代理的。

SpringApplication

Web Environment

Spring Boot applications can now operate in more modes so spring.main.web-environment property is now deprecated in favor of spring.main.web-application-type that provides more control.
If you want to make sure an application doesn’t start a web server you’d have to change the property to:
Tip: there is also a setWebApplicationType on SpringApplication if you want to do that programmatically.

spring.main.web-application-type=none

为了适应响应式编程的新潮流,增加了REACTIVE模式。除了配置属性,也可以编程式实现:

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.setWebApplicationType(WebApplicationType.NONE);
        springApplication.run(args);
    }
Spring Boot Application Events Changes

We’ve added a new event, ApplicationStartedEvent. ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called. ApplicationReadyEvent is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.
See the updated reference documentation.

新增了ApplicationStartingEvent,ApplicationXXXEvent中引入了context上下文。这属于SpringApplicationRunListener 应用监听器功能相关的改进,具体应用可以看EventPublishingRunListener类设计介绍

Banner

In our effort to limit the number of root namespaces that Spring Boot uses, banner-related properties have been relocated to spring.banner.

这是日志、控制台打印的文字图片banner,属性名称增加了spring前缀,顺便百度看到个动态banner。

Externalized Configuration

Relaxed Binding

The rules related to relaxed binding have been tightened
This new relaxed bindings as several advantages:
1.There is no need to worry about the structure of the key in @ConditionalOnProperty: you must now use the canonical format (acme.my-property and not acme.myProperty), the supported relaxed variants will work transparently. If you were using the prefix attribute you can now simply put the full key using the name or value attributes.
2.RelaxedPropertyResolver is no longer available as the Environment takes care of that automatically: env.getProperty("com.foo.my-bar") will find a com.foo.myBar property.
The org.springframework.boot.bind package is no longer available and is replaced by the new relaxed binding infrastructure. In particular, RelaxedDataBinder and friends have been replaced with a new Binder API. The following samples binds MyProperties from the app.acme prefix.

MyProperties target = Binder.get(environment)
        .bind("app.acme", MyProperties.class)
        .orElse(null);

As relaxed binding is now built-in, you can request any property without having to care about the case as long as it’s using one of the supported formats:

FlagType flagType = Binder.get(environment)
        .bind("acme.app.my-flag", FlagType.class)
        .orElse(FlagType.DEFAULT);

1.@ConditionalOnProperty注解匹配属性名称的规则更加严格,不再支持驼峰转换(我试了下,- 和_ 可以互转,离谱),建议配置属性长啥样,匹配名称就怎么写好了。
2.RelaxedPropertyResolver类已经删除了,看了2.0里的实现,一般是用Binder类或Environment类代替实现。
下面也说了,org.springframework.boot.bind整个包都删了,2.0的宽松绑定规则可以看上面的链接,即 new relaxed binding infrastructure。RelaxedDataBinder类也是被Binder类代替实现。

Binding on static methods

While binding on static properties (using a static getter and setter pair) works in Spring Boot 1.x, we never really intended to provide such feature and it is no longer possible as of Spring Boot 2.

这说的应该是给带有 static 关键词的变量 绑定配置属性值(例如:springboot读取yml配置绑定静态属性
),官方不推荐这种做法。

@ConfigurationProperties Validation

It is now mandatory that your @ConfigurationProperties object is annotated with @Validated if you want to turn on validation.

属性配置类里,1.x版本不加@Validated注解,但变量上有@NotNull等校验规则注解亦能执行校验,2.0版本开始必须加上@Validated注解才能执行校验。

Configuration Location

The behavior of the spring.config.location configuration has been fixed; it previously added a location to the list of default ones, now it replaces the default locations. If you were relying on the way it was handled previously, you should now use spring.config.additional-location instead.
读取jar包外部配置用的,比较奇特,还没这样用过,大家可以看下这篇文章spring.config.location与spring.config.additional-location的区别

Developing Web Applications

Embedded containers package structure

In order to support reactive use cases, the embedded containers package structure has been refactored quite extensively. EmbeddedServletContainer has been renamed to WebServer and the org.springframework.boot.context.embedded package has been relocated to org.springframework.boot.web.server. Correspondingly, EmbeddedServletContainerCustomizer has been renamed to WebServerFactoryCustomizer.
For example, if you were customizing the embedded Tomcat container using the TomcatEmbeddedServletContainerFactory callback interface, you should now use TomcatServletWebServerFactory and if you were using an EmbeddedServletContainerCustomizer bean, you should now use a WebServerFactoryCustomizer bean.

为了支持响应式编程,对包做了重构,WebServer新增了NettyWebServer和UndertowWebServer响应式类的web server。WebServerFactoryCustomizer也相应增加了一些实现类。

Servlet-specific server properties

A number of server.* properties that are Servlet-specific have moved to server.servlet:

配置属性名称变化.png
Web Starter as a Transitive Dependency

Previously several Spring Boot starters were transitively depending on Spring MVC with spring-boot-starter-web. With the new support of Spring WebFlux, spring-boot-starter-mustache, spring-boot-starter-freemarker and spring-boot-starter-thymeleaf are not depending on it anymore. It is the developer’s responsibility to choose and add spring-boot-starter-web or spring-boot-starter-webflux.

因为spring-boot-starter-webflux的出现,spring-boot-starter-freemarker等依赖不再包含spring-boot-starter-web,由用户自行引入选择。

Template Engines
Thymeleaf

Spring Boot 2 uses Thymeleaf 3 which has its own migration guide.

In previous version of Spring Boot, the Thymeleaf starter included the thymeleaf-layout-dialect dependency previously. Since Thymeleaf 3.0 now offers a native way to implement layouts, we removed that mandatory dependency and leave this choice up to you. If your application is relying on the layout-dialect project, please add it explicitly as a dependency.

Thymeleaf 3 有了新的layout实现,把方言依赖去掉了,需要的自己引入。

Mustache Templates Default File Extension

The default file extension for Mustache templates was .html, it is now .mustache to align with the official spec and most IDE plugins. You can override this new default by changing the spring.mustache.suffix configuration key.

改了文件后缀,可以通过配置属性 spring.mustache.suffix 自定义。

Jackson / JSON Support

In 2.0, we’ve flipped a Jackson configuration default to write JSR-310 dates as ISO-8601 strings. If you wish to return to the previous behavior, you can add spring.jackson.serialization.write-dates-as-timestamps=true to your configuration.
A new spring-boot-starter-json starter gathers the necessary bits to read and write JSON. It provides not only jackson-databind but also useful modules when working with Java8: jackson-datatype-jdk8, jackson-datatype-jsr310 and jackson-module-parameter-names. If you were manually depending on those modules, you can now depend on this new starter instead.

JSR是指Java 规范提案,JSR-310是关于java8的新日期时间API,ISO-8601 是国际标准化组织提供的一个有关时间表示的规范,显示如1970-01-01T00:00:00Z。springboot2.0里jackson对新日期api序列化做了优化,差异可参考Spring Boot升级到2.x,Jackson对Date时间类型序列化的变化差异,实现原理可参考jackson序列化配置。

Spring MVC Path Matching Default Behavior Change

We’ve decided to change the default for suffix path matching in Spring MVC applications (see #11105). This feature is not enabled by default anymore, following a best practice documented in Spring Framework.
If your application expects requests like "GET /projects/spring-boot.json" to be mapped to @GetMapping("/projects/spring-boot") mappings, this change is affecting you.
For more information about this and how to mitigate that change, check out the reference documentation about path matching and content negotiation in Spring Boot.

GET模式的http请求路径匹配规则取消了后缀路径匹配,如 "http://localhost:8080/test.xxx"不能映射到"http://localhost:8080/test"。

Servlet Filters

The default dispatcher types for a Servlet Filter are now DipatcherType.REQUEST; this aligns Spring Boot’s default with the Servlet specification’s default. If you wish to map a filter to other dispatcher types, please register your Filter using a FilterRegistrationBean.
Note:Spring Security and Spring Session filters are configured for ASYNC, ERROR, and REQUEST dispatcher types.

这个对于使用了Servlet Filters的应用会有影响,可以参考SpringBoot1.5.12升级至2.1.9过程中,由DipatcherType引发的ShiroFilter失效问题。

RestTemplateBuilder

The requestFactory(ClientHttpRequestFactory) method has been replaced by a new requestFactory(Supplier requestFactorySupplier) method. The use of a Supplier allows every template produced by the builder to use its own request factory, thereby avoiding side-effects that can be caused by sharing a factory. See #11255.

RestTemplateBuilder是一个可用于配置和创建RestTemplate的生成de器。提供便捷方法去注册converters, error handlers和UriTemplateHandlers。

WebJars Locator

Spring Boot 1.x used and provided dependency management for org.webjars:webjars-locator. webjars-locator is a "poorly named library … that wraps the webjars-locator-core project". Dependencies on org.webjars:webjars-locator should be updated to use org.webjars:webjars-locator-core instead.

WebJars是将web前端资源(js,css等)打成jar包文件,现在都是前后端分离了,应该没什么人会用了把。

Custom DispatcherServlet registration

If you have customized the registration of the DispatcherServlet, by providing a ServletRegistrationBean named dispatcherServletRegistration, you must also provide a DispatcherServletPath bean so that other components can be aware of the dispatcher servlet’s path. One way to do so is to provide a DispatcherServletRegistrationBean, which implements DispatcherServletPath rather than a ServletRegistrationBean when customizing the registration.

ServletRegistrationBean是将Servlet注册到spring用的,没看懂这段话什么意思。

Security

Tip:This section provides a summary of the changes to security in Spring Boot 2. If you want to know more, refer to the Security migration use cases wiki page.

Spring Boot 2 greatly simplifies the default security configuration and makes adding custom security easy. Rather than having several security-related auto-configurations, Spring Boot now has a single behavior that backs off as soon as you add your own WebSecurityConfigurerAdapter.
You are affected if you were using any of the following properties:

security.basic.authorize-mode
security.basic.enabled
security.basic.path
security.basic.realm
security.enable-csrf
security.headers.cache
security.headers.content-security-policy
security.headers.content-security-policy-mode
security.headers.content-type
security.headers.frame
security.headers.hsts
security.headers.xss
security.ignored
security.require-ssl
security.sessions
Default Security

The security auto-configuration no longer exposes options and uses Spring Security defaults as much as possible. One noticeable side effect of that is the use of Spring Security’s content negotiation for authorization (form login).
Spring Boot 2.0 doesn’t deviate too much from Spring Security’s defaults, as a result of which some of the endpoints that bypassed Spring Security in Spring Boot 1.5 are now secure by default. These include the error endpoint and paths to static resources such as /css/**, /js/**, /images/**, /webjars/**, /**/favicon.ico. If you want to open these up, you need to explicitly configure that.

springboot2.0默认配置了安全属性,可以通过继承WebSecurityConfigurerAdapter自定义安全配置。

Default User

Spring Boot configures a single user with a generated password, by default. The user can be configured using properties under spring.security.user.*. To customize the user further or add other users, you will have to expose a UserDetailsService bean instead. This sample demonstrates how to do it.

在SecurityProperties类中定义了默认用户的属性,可以通过属性配置或者注册InMemoryUserDetailsManager Bean,替换默认实现生成自定义的用户。

To disable default user creation, provide a bean of type AuthenticationManager, AuthenticationProvider or UserDetailsService.
Note:Autowiring an AuthenticationManagerBuilder into a method in a configuration class does not disable creation of the default user.

一般来说,正常应用都是从数据库或其他地方读取用户信息,而不是一个默认用户。参考AuthenticationManager、AuthenticationProvider、UserDetailsService的关系与区别了解AuthenticationManager, AuthenticationProvider和UserDetailsService。

AuthenticationManager Bean

If you want to expose Spring Security’s AuthenticationManager as a bean, override the authenticationManagerBean method on your WebSecurityConfigurerAdapter and annotate it with @Bean.

如果想要将AuthenticationManager声明为Bean,需要覆写WebSecurityConfigurerAdapter类的authenticationManagerBean方法,再加上@Bean注解。

OAuth2

Functionality from the Spring Security OAuth project is being migrated to core Spring Security. Dependency management is no longer provided for that dependency and Spring Boot 2 provides OAuth 2.0 client support via Spring Security 5.
If you depend on Spring Security OAuth features that have not yet been migrated, you will need to add a dependency on an additional jar, check the documentation for more details. We’re also continuing to support Spring Boot 1.5 so older applications can continue to use that until an upgrade path is provided.

依赖合并,没什么好说的。

Actuator Security

There is no longer a separate security auto-configuration for the Actuator (management.security.* property are gone). The sensitive flag of each endpoint is also gone to make things more explicit in the security configuration. If you were relying to this behavior, you need to create or adapt your security configuration to secure endpoints with the role of your choice.
For instance, assuming the following config

endpoints.flyway.sensitive=false
endpoints.info.sensitive=true
management.security.roles=MY_ADMIN

这是配置监控端点安全的,这些配置属性已经不能用了。

http
    .authorizeRequests()
    .requestMatchers(EndpointRequest.to("health", "flyway")).permitAll()
        .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("MY_ADMIN")
        ...

可以通过继承WebSecurityConfigurerAdapter类实现,参考SpringBoot之Actuator。

Note that in 2.x, health and info are enabled by default (with health details not shown by default). To be consistent with those new defaults, health has been added to the first matcher.

Working with SQL Databases

Spring Data Kay renamed a number of its CRUD repository methods. Application code calling the renamed methods will have to be updated. To ease the migration, you may want to consider using a custom CrudRepository sub-interface that declares deprecated default methods that use the old names and delegate to the equivalent newly named method. Marking the default methods has deprecated will help to ensure that the migration is not forgotten.

我也不知道什么方法重命名了,找不到,无语。

Configuring a DataSource

The default connection pool has switched from Tomcat to HikariCP. If you used spring.datasource.type to force the use of Hikari in a Tomcat-based application, you can now remove that override.

默认数据源已切换到HikariCP,不需要再用配置属性强制指定。

In particular, if you had such setup:


    org.springframework.boot
    spring-boot-starter-data-jpa
    
        
            org.apache.tomcat
            tomcat-jdbc
        
    



    com.zaxxer
    HikariCP

you can now replace it with:


    org.springframework.boot
    spring-boot-starter-data-jpa

跟上面一样的意思,已经默认加了。

WARN Message for Implicit 'open-in-view'

From now on, applications that don’t explicitly enable spring.jpa.open-in-view will get a WARN message during startup. While this behavior is a friendly default, this can lead to issues if you’re not fully aware of what’s that doing for you. This message makes sure that you understand that database queries may be performed during view rendering. If you’re fine with that, you can configure explicitly this property to silence the warning message.

没有显式配置则默认为true,应用启动时打印warn日志。这个属性的作用是添加一个拦截器OpenEntityManagerInViewInterceptor,它会改变Session的创建时机和事务的范围,可以参考JPA的使用总结。

JPA

In Spring Boot 1.x, some users were extending from HibernateJpaAutoConfiguration to apply advanced customizations to the auto-configured EntityManagerFactory. To prevent such faulty use case from happening, it is no longer possible to extend from it in Spring Boot 2.

应该是指org.hibernate.jpa.HibernateEntityManagerFactory过期了的事。

To support those use cases, you can now define a HibernatePropertiesCustomizer bean that gives you full control over Hibernate properties, including the ability to register Hibernate interceptor declared as beans in the context.

应该是要实现HibernatePropertiesCustomizer接口,声明注解@Configuration,没有实践过。

Id generator

The spring.jpa.hibernate.use-new-id-generator-mappings property is now true by default to align with the default behaviour of Hibernate. If you need to temporarily restore this now deprecated behaviour, set the property to false.

use-new-id-generator-mappings以前默认为false,现在默认为true,是用来判断选择主键生成策略的,可以参考# SequenceStyleGenerator MySQL 使用注意事项

Flyway

Flyway configuration keys were moved to the spring namespace (i.e. spring.flyway)
Upgrading to Spring Boot 2 will upgrade Flyway from 3.x to 5.x. To make sure that the schema upgrade goes smoothly, please follow the following instructions:

  • First upgrade your 1.5.x Spring Boot application to Flyway 4 (4.2.0 at the time of writing), see the instructions for Maven and Gradle.
  • Once your schema has been upgraded to Flyway 4, upgrade to Spring Boot 2 and run the migration again to port your application to Flyway 5.

If you experience a checksum error on upgrading the schema (i.e. FlywayException: Validate failed. Migration Checksum mismatch), invoking repair could help as show in the following example
Tip:Alternatively, this blog post by @wimdeblauwe provides a different approach that saves the two step upgrade.

@Bean
public FlywayMigrationStrategy repairStrategy() {
    return flyway -> {
        flyway.repair();
        flyway.migrate();
    };
}

Flyway 数据库版本控制的组件,第一次见识。参考介绍Flyway 数据库版本控制。
增加了配置属性的前缀spring。

Liquibase

Liquibase configuration keys were moved to the spring namespace (i.e. spring.liquibase)

增加了配置属性的前缀spring。

Liquibase

Liquibase configuration keys were moved to the spring namespace (i.e. spring.liquibase)

Liquibase 也是数据库版本控制的组件,同样没用过。参考介绍数据库版本控制-liquibase

Database Initialization

Basic DataSource initialization is now only enabled for embedded data sources and will switch off as soon as you’re using a production database. The new spring.datasource.initialization-mode (replacing spring.datasource.initialize) offers more control.

这个属性是用来判断是否执行初始化sql的。拓展知识springboot 启动时初始化数据库的步骤

Updated Default 'create-drop' Handling

The spring.jpa.hibernate.ddl-auto property defaults to create-drop with an embedded database only if no schema manager, such as Liquibase or Flyway, is in use. As soon as a schema manager is detected, the default changes to none.

spring.jpa.hibernate.ddl-auto 实际对应属性 hibernate.hbm2ddl.auto,用来控制表结构的更改,甚至创建和删除。当连接嵌入式数据库时,默认 create-drop,其他默认none。
拓展知识Spring Boot初始化数据库和导入数据以及spring.jpa.generate-dll与spring.jpa.hibernate.ddl-auto之间的困惑。

Working with NoSQL Technologies

Redis

Lettuce is now used instead of Jedis as the Redis driver when you use spring-boot-starter-data-redis. If you are using higher level Spring Data constructs you should find that the change is transparent.
We still support Jedis. Switch dependencies if you prefer Jedis by excluding io.lettuce:lettuce-core and adding redis.clients:jedis instead.

redis客户端依赖Jedis默认替换为Lettuce。

Connection pooling is optional and, if you are using it, you now need to add commons-pool2 yourself as Lettuce, contrary to Jedis, does not bring it transitively.

Jedis是直连redis的,所以一个请求对应一次连接开关,比较消耗性能,所以配置连接池很有必要。Lettuce是基于netty的连接实例,不需要连接池也能共享连接,如果连接池使用不当,反而还会降低性能。拓展知识lettuce连接池真有必要吗?。

Elasticsearch

Elasticsearch has been upgraded to 5.4+. In line with Elastic’s announcement that embedded Elasticsearch is no longer supported, auto-configuration of a NodeClient has been removed. A TransportClient can be auto-configured by using spring.data.elasticsearch.cluster-nodes to provide the addresses of one or more nodes to connect to.

官方不再支持嵌入式Elasticsearch ,因为它绕过了安全管理、插件加载等机制。节点配置方式发生了改变。

Caching

Dedicated Hazelcast Auto-configuration for Caching

It is no longer possible to auto-configure both a general HazelcastInstance and a dedicated HazelcastInstance for caching. As a result, the spring.cache.hazelcast.config property is no longer available.

Hazelcast是一个基于内存的计算存储平台,擅长流数据处理,没用过,不多做解释。

GuavaCacheManager

Support for Guava has been dropped in Spring Framework 5. If you were are using GuavaCacheManager, Caffeine (com.github.ben-manes.caffeine:caffeine) and CaffeineCacheManager should be used instead.

在spring5中,有以下几种本地缓存实现:
CaffeineCache:基于Caffeine组件实现。
ConcurrentMapCache:基于java的ConcurrentMap实现。
EhCacheCache:基于EhCache组件实现。
JCacheCache:基于javax.cache实现。
NoOpCache:禁用缓存操作实现。这个实现的目的在于通过编写配置的方式便捷切换缓存的使用与禁用,如@Profeile。
TransactionAwareCacheDecorator:缓存装饰器,具体实现由注入的Cache决定。需要配合spring事务使用,在事务提交后执行cache操作,相当于Read Committed级别。拓展知识TransactionAwareCacheDecorator升级版。

RedisCacheManager

The Redis CacheManager implementation has been reworked significantly, make sure to review the reference documentation.

RedisCacheManager被重写了,现在可以将其配置为Bean,方便用户自定义。

Batch

The CommandLineRunner that executes batch jobs on startup has an order of 0.

这是指实现类JobLauncherCommandLineRunner,现在实现了Ordered接口,默认orderrder顺序为0。

Testing

Mockito 1.x

Mockito 1.x is no longer supported for @MockBean and @SpyBean. If you don’t use spring-boot-starter-test to manage your dependencies you should upgrade to Mockito 2.x.
Note:See also What’s new in Mockito 2

没用过Mockito,使用参考SpringBoot 单元测试详解(Mockito、MockBean)。

EnvironmentTestUtils

EnvironmentTestUtils is deprecated in favour of TestPropertyValues that offers a similar, yet more powerful API as demonstrated in the following example:

TestPropertyValues.of("acme.first=1", "acme.second=2")
        .and("acme.third=3")
        .applyTo(this.environment);

EnvironmentTestUtils 应替换为 TestPropertyValues。

Creating Your Own Auto-configuration

ConditionalOnBean semantic change

ConditionalOnBean is now using a logical AND rather than an OR for candidate beans. If you need to keep a condition where any of the target beans are present, consider using a AnyNestedCondition as shown in the following example:

class ThisOrThatCondition extends AnyNestedCondition {

    ThisOrThatCondition() {
        super(ConfigurationPhase.REGISTER_BEAN);
    }

    @ConditionalOnBean(This.class)
    static class ThisCondition {

    }

    @ConditionalOnBean(That.class)
    static class ThatCondition {

    }

}

ConditionalOnBean 的条件语义发生变化,当设置了多个类时,如@ConditionalOnBean(xxx.class,xxx.class),OR条件改为AND条件。

Spring Boot Actuator

Spring Boot 2 brings important changes to the actuator, both internal and user-facing, please check the updated section in the reference guide and the new Actuator API documentation.

监控平台升级没啥好说的,参考介绍springboot 的指标监控。

Build

The code of the Actuator has been split in two modules: the existing spring-boot-actuator and a new spring-boot-actuator-autoconfigure. If you were importing the actuator using its original module (spring-boot-actuator), please consider using the spring-boot-starter-actuator starter instead.

actuator依赖升级,建议更换新的依赖。

Configuration Keys Structure

Endpoints infrastructure key have been harmonized:


配置属性

配置属性新老交替,替换下就好了。

Base Path

All endpoints have moved to /actuator by default.
We fixed the meaning of management.server.servlet.context-path: it is now the endpoint management equivalent of server.servlet.context-path (only active when management.server.port is set). Additionally, you can also set the base path for the management endpoints with a new, separate property: management.endpoints.web.base-path.
For example, if you’ve set management.server.servlet.context-path=/management and management.endpoints.web.base-path=/application, you’ll be able to reach the health endpoint at the following path: /management/application/health.

actuator 的端点基础路径默认为 /actuator,如http://localhost:8080/actuator/health;当 management.endpoints.web.base-path=/manage,那么http://localhost:8080/manage/health;当management.server.servlet.context-path=/management 单独使用,无法生效,要加上 management.server.port=8082,如http://localhost:8082/management/actuator/health;当 management.endpoints.web.base-path=/application,那么 http://localhost:8082/application/health;三条属性同时配置,那么 http://localhost:8082/management/application/health。

If you want to restore the behavior of 1.x (i.e. having /health instead of /actuator/health), set the following property:

management.endpoints.web.base-path=/

通过此配置,可以还原到actuator 1.x的路径格式。

Audit Event API Change

AuditEventRepository now has a single method with all optional arguments.

AuditEventRepository 用来添加AuditEvent的。AuthenticationAuditListener定义了三个事件用于监听,AUTHENTICATION_SUCCESS、AUTHENTICATION_FAILURE、AUTHENTICATION_SWITCH,并要求配合spring security使用。用户可以在端点 /auditevents 下查看审计事件。参考Springboot Actuator之十:actuator中的audit包和Spring Boot Actuator。

Endpoints

To make an actuator endpoint available via HTTP, it needs to be both enabled and exposed. By default:

  • Only the /health and /info endpoints are exposed, regardless of Spring Security being present and configured in your application.
  • All endpoints but /shutdown are enabled.

端点需要启用并公开才能访问,默认只公开 /health 和 /info,除 /shutdown 外其他端点都是启用的。

You can expose all endpoints as follows:

management.endpoints.web.exposure.include=*

公开所有端点。

You can explicitly enable the /shutdown endpoint with:

management.endpoint.shutdown.enabled=true

启用 /shutdown 端点。

To expose all (enabled) web endpoints but the env endpoint:

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env

公开除env端点之外的所有(已启用)web端点。


端点变更

Endpoint properties have changed as follows:

  • endpoints..enabled has moved to management.endpoint..enabled
  • endpoints..id has no replacement (the id of an endpoint is no longer configurable)
  • endpoints..sensitive has no replacement (See Actuator Security)
  • endpoints..path has moved to management.endpoints.web.path-mapping.

端点配置属性变化。

Endpoint Format

Overhaul of the "/actuator/mappings" Actuator Endpoint

The JSON format has changed to now properly include information about context hierarchies, multiple DispatcherServlets, deployed Servlets and Servlet filters. See #9979 for more details.
The relevant section of the Actuator API documentation provides a sample document.

/mappings 端点可以查看 @RequestMapping 下的请求路径映射的json列表,2.x的json格式变了,看不出有啥影响。

Overhaul of the "/actuator/httptrace" Actuator Endpoint

The structure of the response has been refined to reflect the endpoint’s focus on tracing HTTP request-response exchanges. More details about the endpoint and its response structure can be found in the relevant section of the Actuator API documentation.

/httptrace 端点可以查看http请求信息,2.x的json格式变了。

Migrate Custom Endpoints

If you have custom actuator endpoints, please check out the dedicated blog post. The team also wrote a wiki page that describes how to migrate your existing Actuator endpoints to the new infrastructure.

1.x和2.x的端点实现方式变了很多,参考actuator 2.x 自定义实现端点。

Metrics

Spring Boot’s own metrics have been replaced with support, including auto-configuration, for Micrometer and dimensional metrics.

Setting up Micrometer

If your Spring Boot 2.0 application already depends on Actuator, Micrometer is already here and auto-configured. If you wish to export metrics to an external registry like Prometheus, Atlas or Datadog, Micrometer provides dependencies for many registries; you can then configure your application with spring.metrics.* properties to export to a particular registry.
For more on this, check out the Micrometer documentation about Spring Boot 2.0.

Micrometer 是一个基于 JVM 的应用程序指标收集工具包,提供了抽象接口和脱离底层的第三方监控依赖,类似于 SLF4J 在 Java 日志中的作用。参考介绍Spring Boot集成Micrometer。

Migrating Custom Counters/Gauges

Instead of injecting CounterService or GaugeService instances in your application code, you can create various metrics by:

  • Injecting a MeterRegistry and calling methods on it.
  • Directly calling static methods like Counter featureCounter = Metrics.counter("feature");.
    Micrometer brings many interesting features - check out the core concepts behind Micrometer and the specifics about Spring Boot integration.

可以参考上面的链接文章。

Spring Boot 1.5 Support

You can plug existing Spring Boot 1.5 applications in the same metrics infrastructure by using the Micrometer Legacy support.

网站打不开,后面再看。

Developer Tools

Hot swapping

As the Spring Loaded project has been moved to the attic, its support in Spring Boot has been removed. We advise to use Devtools instead.

Spring Loaded项目被搁置,推荐spring-boot-devtools。
Spring Loaded自2017年9月后,版本就没有升级过了,看来是被放弃了。

Devtools Remote Debug Tunnel

The support for tunnelling remote debugging over HTTP has been removed from Devtools.

devtools 通过 HTTP 进行远程调试,这个功能被删除了。

Removed Features

The following features are no longer available:

  • CRaSH support
  • Auto-configuration and dependency management for Spring Mobile.
  • Auto-configuration and dependency management for Spring Social. Please check the Spring Social project for more details.
  • Dependency management for commons-digester.
  • Test support in the CLI (i.e. spring test)

CRaSH support:远程执行命令。
Auto-configuration and dependency management for Spring Mobile:spring-mobile是基于模板引擎开发的框架,在前后端分离趋势下,项目废弃是理所当然的。
Auto-configuration and dependency management for Spring Social. Please check the Spring Social project for more details:为什么放弃spring social项目及替代方案。
Dependency management for commons-digester:ommons-digester工具包的作用是将xml转换为java对象。
Test support in the CLI (i.e. spring test):我的理解是spring-test不支持spring-boot-CLI。Spring Boot CLI是Spring Boot的命令行界面,使用groovy语言编写,它可以用来快速启动Spring。

Dependency Versions

The minimum supported version of the following libraries has changed:

  • Elasticsearch 5.6
  • Gradle 4
  • Hibernate 5.2
  • Jetty 9.4
  • Spring Framework 5
  • Spring Security 5
  • Spring Integration 5 (see also their migration guide)
  • Tomcat 8.5

最小依赖版本支持。

总结

这篇文章的编写耗时超过了我的预期,涉及知识点广泛,想要尽可能地理解每一点,需要花不少时间,即使如此,依然有很多理解偏颇(希望有人能指正)。不过写完后,发现自己也的确有所收获。不管在面试还是日常工作中,我们都需要知道自己所用何物,才能物尽其用,所以当工具发生变化时,及时了解变化之所在,是很有必要的。

迁移指南中文翻译

https://blog.51cto.com/u_14299052/2935938

你可能感兴趣的:(Spring Boot 2.0 迁移指南(1.5升级2.0版本特性变化))