很多时候,我们需要把maven dependency 的版本定义为变量,这样就能够更好地对后续的项目更新升级。
最近掉进maven的坑就是在多模块的maven项目中,如果我们每个项目之间互相依赖,如果根项目中设置了denpendency版本号变量就会导致“隔代”模块中的dependency无法找到。出现以下的error。
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${openapi.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
[WARNING] The POM for org.springdoc:springdoc-openapi-ui:jar:${openapi.version} is missing, no dependency information available
[WARNING] The POM for org.mybatis.spring.boot:mybatis-spring-boot-starter:jar:${mybatis.version} is missing, no dependency information available
对于解决这样的问题,maven官方提供了optional denpendency的解决办法:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${openapi.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
<optional>true</optional>
</dependency>
How do optional dependencies work?
- Project-A -> Project-B
The diagram above says that Project-A depends on Project-B. When A declares B as an optional dependency in its POM, this relationship remains unchanged. It's just like a normal build where Project-B will be added in Project-A's classpath.
- Project-X -> Project-A
When another project (Project-X) declares Project-A as a dependency in its POM, the optional nature of the dependency takes effect. Project-B is not included in the classpath of Project-X. You need to declare it directly in the POM of Project X for B to be included in X's classpath.
Suppose there is a project named X2 that has similar functionality to Hibernate. It supports many databases such as MySQL, PostgreSQL, and several versions of Oracle. Each supported database requires an additional dependency on a driver jar. All of these dependencies are needed at compile time to build X2. However your project only uses one specific database and doesn't need drivers for the others. X2 can declare these dependencies as optional, so that when your project declares X2 as a direct dependency in its POM, all the drivers supported by the X2 are not automatically included in your project's classpath. Your project will have to include an explicit dependency on the specific driver for the one database it does use.
当在多模块Maven项目中使用变量定义依赖版本时,可能会遇到间接依赖找不到的问题。Maven的optional依赖提供了解决方案。optional依赖意味着在依赖传递过程中,该依赖不会被包含在依赖项目的类路径中,除非直接声明。这样可以避免不必要的依赖冲突和减少构建负担。例如,项目A依赖于项目B,B依赖于X,如果X的某些依赖标记为optional,那么在项目A中不需要直接声明这些依赖也能正常构建。但在项目X的使用者如项目Y中,若需要这些optional依赖,则必须在Y的POM中显式声明。
2443

被折叠的 条评论
为什么被折叠?



