很多时候,我们需要把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?

  1. 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.

 
  1. 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.

Example

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 Module 互相依赖no dependency information available的问题