gradle中如何实现maven的bom功能

在maven里有 bom (bill of materials) 的功能,可以解决同一项目,不同版本依赖的问题。

gradle虽然是“下一代maven”替代品,但并没有原生的支持bom这一强大的功能。

有两个方案可以搞定类似的需求:

本文主要介绍后者的用法

TL;DR:参考写好的两个项目 pom-parent-test (bom) 和 pom-gradle-test (子工程)

1、先看bom项目

我们创建一个标准的bom项目,如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.coder4.sbmvt</groupId>
    <artifactId>pom-parent</artifactId>
    <version>0.0.1</version>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
        <spring.boot.version>1.5.6.RELEASE</spring.boot.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
	    <dependency>
	        <groupId>com.google.guava</groupId>
	        <artifactId>guava</artifactId>
	        <version>23.0</version>
	    </dependency>
        </dependencies>
    </dependencyManagement>

    <distributionManagement>
        <repository>
            <id>nexus_coder4</id>
            <url>http://maven.coder4.com/nexus/content/repositories/releases/</url>
        </repository>
        <snapshotRepository>
            <id>nexus_coder4</id>
            <url>http://maven.coder4.com/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
</project>

如上所述,这里和maven的bom没有什么不同,末尾的maven是我自己的私服,请替换成你自己的。

2、子项目使用

// 引入插件
plugins {
    id "io.spring.dependency-management" version "1.0.3.RELEASE"
}

apply plugin: 'java'
apply plugin: 'application'

repositories {
    // 使用阿里云镜像加速
    maven { url 'http://maven.aliyun.com/nexus/content/groups/public' }
    mavenLocal()
}

// import bom
dependencyManagement {
    imports {
        mavenBom 'com.coder4.sbmvt:pom-parent:0.0.1'
    }
}

dependencies {
    // bom会帮忙填充版本
    compile 'org.springframework.boot:spring-boot-starter-web'
    // 你也可以自己指定版本,会根据两者取一个合理不冲突的值
    testCompile 'junit:junit:4.12'
}

// Define the main class for the application
mainClassName = 'App'

 

是不是很简单?

 

 

1 thought on “gradle中如何实现maven的bom功能

  1. Pingback: Spring boot and spring cloud version management (gradle version) – Newbie tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *