Maven 多模块项目依赖管理
来源:原创 发布时间:2015-04-19 归档:maven
环境 :
JDK 7
Maven 3
Tomcat 7
Eclipse Luna
继 Maven 多模块项目 一文, 下面介绍在多模块项目中, 如何管理项目的依赖。
dependencyManagement
<project>
[. . .]
<artifactId>kitty-parent</artifactId>
<modules>
<module>kitty-app</module>
<module>kitty-core</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
</dependencyManagement>
[. . .]
</project>
这是父模块 kitty-parent 的配置片段, 以上声明依赖的方式与以往稍有不同, 上面用了 <dependencyManagement> 节点, 这样配置完成之后, 实质上, 子模块不会引入任何的构件依赖, 这样做只是为了让子模块能够继承得到这些配置, 这样做的好处是, 在子模块中只需要声明 groupId 和 artifactId 就能准确无误的获取得到依赖的构件。可以想象的到, 这样一来, 不仅能够使子模块配置依赖变得简单, 还能使项目范围内所有依赖的构件的版本能够得到统一, 而且还能在父模块中统一的来管理, 这样就不会发生在多个子模块项目中使用构件的版本不一致的问题。
pluginManagement
<project>
[. . .]
<artifactId>kitty-parent</artifactId>
<modules>
<module>kitty-app</module>
<module>kitty-core</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler.version}</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire.version}</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
[. . .]
</project>
pluginManagement 用于插件的管理, 作用与 dependencyManagement 雷同, 这里不再赘述。
kitty-core pom
<project> <parent> <groupId>org.lychie</groupId> <artifactId>kitty-parent</artifactId> <version>1.0.0</version> </parent> <artifactId>kitty-core</artifactId> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> </plugin> </plugins> </build> </project>
这是子模块项目 kitty-core 的配置片段, 可以看到, 它在使用依赖和插件时, 都只需要声明 groupId 和 artifactId。
示例代码下载