我正在使用Maven,我想在不重复某些必需依赖项的情况下执行插件:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
</dependency>
<!-- ^^^ unnecessary duplication, IMO, because the project
already imports the dependency below -->
</dependencies>
<!-- ... -->
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
</dependency>
</dependencies>
在上面的例子中,我想省略com.h2database:h2
依赖项,因为我已经在项目中指定了它。可以这样做吗?怎么样?
答案 0 :(得分:3)
您可以通过在父级中使用pluginManagement块来执行此操作:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.3.168</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</pluginManagement>
在你的孩子中,你只需要使用这样的执行:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<executions>
<execution>
....
</execution>
</executions>
</plugin>
</plugins>
</build>
这将解决您的问题,只能在一个地方维护补充类路径依赖项(h2)。
答案 1 :(得分:0)
虽然插件不会自动从包含它们的模块/项目继承依赖项(see khmarbaise's answer),但插件作者仍然可以以模块/项目类路径的方式实现其插件也适用于插件。例如,Flyway migration plugin或jOOQ代码生成器就是这样做的。
在插件中如何做到这一点的一个例子是:
@Mojo
public class Plugin extends AbstractMojo {
@Parameter(property = "project", required = true, readonly = true)
private MavenProject project;
@Override
public void execute() throws MojoExecutionException {
ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(getClassLoader());
// Plugin logic
}
finally {
Thread.currentThread().setContextClassLoader(oldCL);
}
}
@SuppressWarnings("unchecked")
private ClassLoader getClassLoader() throws MojoExecutionException {
try {
List<String> classpathElements = project.getRuntimeClasspathElements();
URL urls[] = new URL[classpathElements.size()];
for (int i = 0; i < urls.length; i++)
urls[i] = new File(classpathElements.get(i)).toURI().toURL();
return new URLClassLoader(urls, getClass().getClassLoader());
}
catch (Exception e) {
throw new MojoExecutionException("Couldn't create a classloader.", e);
}
}
}