1. 程式人生 > >Maven的dependency和dependencyManagement的區別

Maven的dependency和dependencyManagement的區別



dependencies:

就算在子專案中不寫該依賴項,那麼子專案仍然會從父專案中繼承該依賴項(全部繼承)

dependencyManagement:

只是宣告依賴,並不實現引入,因此子專案需要顯示宣告需要用的依賴。如果不在子專案中宣告依賴,是不會從父專案中繼承下來的;只有在子專案中寫了該依賴項,並且沒有指定具體版本,才會從父專案中繼承該項,並且version和scope都讀取自父pom;另外如果子專案中指定了版本號,那麼會使用子專案中指定的jar版本。

例子:

父專案pom.xml

<properties>
	<springframework.version>2.5.6</springframework.version>
	<junit.version>4.7</junit.version>
</properties>
<dependencyManagement>  
          
        <dependencies>  
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-core</artifactId>  
                <version>${springframework.version}</version>
            </dependency>  
              
            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-beans</artifactId>  
                <version>${springframework.version}</version>  
            </dependency>  

            <dependency>  
                <groupId>org.springframework</groupId>  
                <artifactId>spring-context</artifactId>  
                <version>${springframework.version}</version>  
            </dependency>  
        </dependencies>  
    </dependencyManagement>  


這裡使用dependencyManagement宣告的依賴既不會給父專案引入依賴,也不會給他的子模組引入依賴,不過這段配置是會被繼承

用到父專案的依賴的子專案pom.xml配置

<dependencies>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-core</artifactId>
    </dependency>  
      
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-beans</artifactId>
    </dependency>  

    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-context</artifactId>
    </dependency>  
</dependencies>  


不需要父專案的依賴的子專案pom.xml配置,只需要引入父專案的依賴即可

<dependencies>  
    <dependency>  
        <groupId>dom4j</groupId>  
        <artifactId>dom4j</artifactId>
	<version>${dom4j.version}</version>
    </dependency>  
      
    <dependency>  
        <groupId>junit</groupId>  
        <artifactId>junit</artifactId>
    </dependency>
</dependencies>  

這裡沒有宣告父專案的依賴,那麼該依賴就不會被引入。這正是dependencyManagement的靈活性所在。


import依賴範圍

import範圍只有在denpendencyManagement元素下才有效果

如果你想要把專案A專案的依賴用於另外一個專案就需要使用import範圍將這配置匯入

<dependencyManagement>  
          
        <dependencies>  
            <dependency>  
                <groupId>com.mvnbook.account</groupId>  
                <artifactId>account-parent</artifactId>  
                <version>1.0-SNAPSHOT</version>
		<type>pom</type>
		<scope>import</scope>
            </dependency>  
        </dependencies>  
    </dependencyManagement>  


上述程式碼中type的值為pom,import範圍由於其特殊性,一般都是指向打包型別為pom的模組。如果有多個先忙,他們使用的版本都是一致的,則就可以定義一個使用

dependencyManagement專門管理依賴的POM,然後在各個專案中匯入這些依賴管理配置