在遗留项目中使用 Spring Boot and Cloud
几年前还没有Spring Booot的时候,公司Maven项目里一般都定义了自己的parent pom,规范了可用的第三方类库。在这样的系统里如何引进Spring Boot,Spring Clould这样的工具呢?这篇官方文档介绍了在已有parent pom的情况下如何使用boot。
下面算是几个学习摘要。
1) 如果遗留项目中没有使用自己parent pom,那么在项目模块中就可以直接设置parent为spring-boot-starter-parent
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.6.RELEASE</version>
</parent>
如果想更改某个子项目版本,通过下面设置属性的方式进行更改。
<properties>
<spring-data-releasetrain.version>Fowler-SR2</spring-data-releasetrain.version>
</properties>
查看有哪些可更改的properties,参考这里。
2)如果已有的maven项目中已经存在parent pom,那么可以通过 denpendencyManagemengt的方式指定boot的BOM。
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
这种情况下,如果需要指定某个版本的库,就需要在定义spring-boot-dependencies的前面定义dependence了。就像下面这样,spring-data-releasetrain使用了不同于1.3.6.RELEASE的另一个版本Fowler-SR2。
<dependencyManagement>
<dependencies>
<!-- Override Spring Data release train provided by Spring Boot -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>Fowler-SR2</version>
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.6.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
3)关于Maven中BOM[Bill Of Materials]的概念。
这篇文章讲得不错:http://howtodoinjava.com/maven/maven-bom-bill-of-materials-dependency/。
A BOM dependency keep track of version numbers and ensure that all dependencies (both direct and transitive) are at the same version.
4) 如何添加BOM依赖?
maven通过dependencyManagement来支持BOM。比如像下面这样加入Spring BOM。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.0.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
那么,以后再使用那个这个BOM包含的库时,就不必制定version了。比如:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependencies>
在__dependencyManagement下的声明不会引入实际的依赖__,它仅仅__用来约束dependencies__下面的依赖使用。
虽然这个BOM概念很赞,但是不要幻想有什么通用的BOM。每个项目都有它自己的BOM文件用来管理用到的库依赖。
5) 图例
下图用来说明一下从start.spring.io网站,生产的模版项目中,pom.xml对SpringBoot,SpringCloud作为BOM的使用。一般地,我们应该把这这些BOM定义在作为parent使用的pom里进行集中地、统一地管理。