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

使用org.apache.maven.Model向Maven pom.xml添加依赖遇Groovy异常

Fixing Groovy MissingMethodException When Adding Maven Dependency via org.apache.maven.Model

Hey there! Let's break down why you're hitting that Groovy.lang.MissingMethodException and get your dependency added properly.

What's Causing the Error?

The issue is that you're trying to use newInstance() on the Dependency class with a LinkedHashMap, but Maven's Dependency class doesn't have a constructor that accepts a map directly. The newInstance() method you're calling expects either no arguments or values that match one of the class's defined constructors—not a map of property names and values.

Working Solutions

Here are a few clean ways to add the dependency correctly:

1. Explicitly Create and Configure a Dependency Instance

This straightforward approach lets you manually set each property of the dependency:

def model = readMavenPom file: 'pom.xml'

// Initialize a new Dependency object
def dep = new org.apache.maven.model.Dependency()
dep.groupId = "org.foo"
dep.artifactId = "bar"
// Optional: Add other properties like version or scope
// dep.version = "1.0.0"
// dep.scope = "compile"

// Add the dependency to the pom model
model.addDependency(dep)

// Save your changes back to the actual pom.xml file
writeMavenPom model: model

2. Use Groovy's Map-to-JavaBean Conversion

Groovy has a handy built-in feature that converts a map to a JavaBean automatically (as long as map keys match the bean's property names):

def model = readMavenPom file: 'pom.xml'

def depMap = [groupId: "org.foo", artifactId: "bar"]
// Convert the map to a Dependency instance
def dep = depMap as org.apache.maven.model.Dependency

model.addDependency(dep)
writeMavenPom model: model

3. Inline Dependency Creation

For a more compact solution, create the Dependency directly inside the addDependency call using Groovy's named parameter syntax:

def model = readMavenPom file: 'pom.xml'

model.addDependency(new org.apache.maven.model.Dependency(
    groupId: "org.foo",
    artifactId: "bar"
    // Add optional properties here if needed
    // version: "1.0.0"
))

writeMavenPom model: model

Important Note

Don't skip the writeMavenPom call at the end—this is what persists your changes back to the actual pom.xml file. Without it, your new dependency won't be saved!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:02:44