You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Maven子项目使用与父项目不同版本并解决依赖解析错误?

解决Maven父子项目子项目独立版本的依赖问题

问题根源

你修改子项目版本为0.9.2-SNAPSHOT后,依赖中的${project.version}会自动替换为子项目的版本,但你依赖的parent-dev包实际上只有父项目的0.9.1-SNAPSHOT版本,导致Maven无法解析到对应版本的依赖。

解决方案

方案1:为父项目相关依赖单独指定版本

直接在子项目的依赖中明确使用父项目的版本,或者通过父项目定义的属性来引用:

  1. 在父项目的properties中定义自身版本属性:
    <properties>
        <parent.project.version>0.9.1-SNAPSHOT</parent.project.version>
    </properties>
    
  2. 在子项目的依赖中使用这个属性,替代${project.version}:
    <dependency>
        <groupId>io.parent-dep</groupId>
        <artifactId>parent-dev</artifactId>
        <version>${parent.project.version}</version>
    </dependency>
    
  3. 子项目保留独立版本配置:
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>io.parent-test</groupId>
        <artifactId>io.parent-test</artifactId>
        <version>0.9.1-SNAPSHOT</version>
        <relativePath></relativePath>
    </parent>
    
    <version>0.9.2-SNAPSHOT</version>
    <artifactId>test-project-converter</artifactId>
    <name>test-project</name>
    <description>Test Project</description>
    

方案2:规范使用Maven版本属性管理

如果希望统一管理版本避免硬编码,可以调整属性使用方式:

  1. 父项目中定义自身版本和子项目独立版本的属性:
    <properties>
        <parent.revision>0.9.1-SNAPSHOT</parent.revision>
        <child.converter.revision>0.9.2-SNAPSHOT</child.converter.revision>
    </properties>
    
  2. 父项目的version引用自身版本属性:
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.parent-test</groupId>
    <artifactId>io.parent-test</artifactId>
    <version>${parent.revision}</version>
    
  3. 子项目中用父项目版本属性引用依赖,同时使用自身版本属性:
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>io.parent-test</groupId>
        <artifactId>io.parent-test</artifactId>
        <version>${parent.revision}</version>
        <relativePath></relativePath>
    </parent>
    
    <version>${child.converter.revision}</version>
    <artifactId>test-project-converter</artifactId>
    <name>test-project</name>
    <description>Test Project</description>
    
    <dependencies>
        <dependency>
            <groupId>io.parent-dep</groupId>
            <artifactId>parent-dev</artifactId>
            <version>${parent.revision}</version>
        </dependency>
    </dependencies>
    

注意事项

  • ${project.version}始终指向当前项目(子/父项目)的版本,子项目有独立版本时,它会指向子项目版本,不适合引用父项目相关依赖的版本。
  • 如果父项目使用<dependencyManagement>管理依赖版本,子项目中直接省略依赖版本即可,Maven会自动继承父项目中管理的版本。

内容的提问来源于stack exchange,提问作者BATMAN_2008

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:05:26