概述
在之前的Spring Boot例子中,我們都會用到這樣的parent POM。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
這個parent指定了spring-boot所需要的依賴。但是有時候如果我們的項目已經有一個parent了,這時候需要引入spring boot該怎么處理呢?
本文將會解決這個問題。
不使用Parent POM來引入Spring boot
parent pom.xml主要處理的是依賴和使用的插件管理。使用起來會非常簡單,這也是我們在Spring boot中常用的方式。
在實際中,如果我們因為種種原因,不能使用Spring boot自帶的parent,那么我們可以這樣做:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
將spring-boot-dependencies作為一個依賴放入dependencyManagement標簽即可。注意,這里的scope要使用import。
接下來,我們就可以隨意使用spring boot的依賴了,例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
另一方面,如果不使用parent POM,Spring boot自帶的plugin,需要我們自己引入:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
覆蓋依賴項版本
如果我們需要使用和parent POM中定義的不同的依賴項版本,則可以在dependencyManagement中重寫。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.5.RELEASE</version>
</dependency>
</dependencies>
// ...
</dependencyManagement>
當然,你也可以在每次引入依賴的時候,指定所需要的版本。
更多教程請參考 flydean的博客