亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Maven中靈活統一添加依賴

標簽:
Java

依赖继承

在一个大型Maven项目中,往往包含多个子项目,而这些子项目很有可能都引用了相同的依赖,所以可以在parent pom中进行依赖的设置,以便子项目进行继承,进而减少重复的设置。

例如在parent pom中添加spring-boot-starter-web依赖,那么所有子项目就都获得了这个依赖。

            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
            </dependencies>

选择性继承

但是在有些情况下,有可能只有一部分子项目需要这个依赖,其他子项目是不需要的,这时候在parent pom中直接添加dependency就不合适了,因为它会被所有的子项目直接继承。如果我们需要选择性继承,则可以使用profile。

首先,我们在parent pom中添加一个profile,在profile中我们设置依赖。

    <profiles>
        <profile>
            <id>web</id>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

接下来需要设置何时激活profile,来达到选择性继承的目的。

property activation的bug

profile的激活有很多种,一眼看上去最合适的就是property,官方文档上对它如下说明

property: The profile will activate if Maven detects a property (a value which can be dereferenced within the POM by ${name}) of the corresponding name=value pair.

那么假设如下的profile

    <profiles>
        <profile>
            <id>web</id>
            <activation>
                <property>
                    <name>type</name>
                    <value>web</value>
                </property>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

那么在需要这个依赖的子项目中设置以下properties不就好了么?

    <properties>
        <type>web</type>
    </properties>

然而事实证明想多了,这个properties只能是system property。
https://issues.apache.org/jira/browse/MNG-6851

最终实现选择性继承

这样只能考虑用file来进行选择性依赖了。

    <profiles>
        <profile>
            <id>web</id>
            <activation>
                <file>
                    <exists>${basedir}/web</exists>
                </file>
            </activation>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

在需要依赖的子项目中建立web文件,就可以获得相关依赖了。

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消