多模块管理Dependency
- 参考链接:
https://www.infoq.cn/article/2011/01/xxb-maven-3-pom-refactoring
- dependency和dependencyManagement的区别
要对项目中的所有模块使用相同版本的依赖,可以在父模块中配置 dependencies,那样所有子模块都自动继承,不仅达到了依赖一致的目的,还省掉了大段代码,但这么做是有问题的,例如你将模块 C 的依赖 spring-aop 提取到了父模块中,但模块 A 和 B 虽然不需要 spring-aop,但也直接继承了。dependencyManagement 就没有这样的问题,dependencyManagement 只会影响现有依赖的配置,但不会引入依赖。
使用import scope
在使用 dependencyManagement 的时候,我们可以不从父模块继承,而是使用特殊的 import scope 依赖。
我们知道 Maven 的继承和 Java 的继承一样,是无法实现多重继承的,如果 10 个、20 个甚至更多模块继承自同一个模块,那么按照我们之前的做法,这个父模块的 dependencyManagement 会包含大量的依赖。如果你想把这些依赖分类以更清晰的管理,那就不可能了,import scope 依赖能解决这个问题。你可以把 dependencyManagement 放到单独的专门用来管理依赖的 POM 中,然后在需要使用依赖的模块中通过 import scope 依赖,就可以引入 dependencyManagement。
Dependency scope
- 参考链接:
https://uule.iteye.com/blog/2087485
6 scopes
Dependency scope is used to limit the transitivity of a dependency, and also to affect the classpath used for various build tasks.
There are 6 scopes available:
- compile
This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
- provided
This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.
- runtime
This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
- test
This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. This scope is not transitive.
- system
This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
- import
This scope is only supported on a dependency of type pom in the <dependencyManagement>
section. It indicates the dependency to be replaced with the effective list of dependencies in the specified POM's <dependencyManagement>
section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.