使用org.apache.maven.Model向Maven pom.xml添加依赖遇Groovy异常
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

