插件如何添加自己生成的资源?

How can a plugin add its own generated resources?

此问题与 maven: How to add resources which are generated after compilation phase 中提出的解决方案完全相同,但我正在寻找另一个解决方案。

在我的插件中,我成功地在 target/generated-resources/some 目录中生成了一些资源文件。

现在我希望这些资源文件包含在托管项目的最终 jar 中。

我试过了。

final Resource resource = new Resource();
resource.setDirectory("target/generated-resources/some");
project.getBuild().getResources().add(resource);

其中 project 是这样定义的。

@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;

而且它不起作用。

编译阶段后,不再调用Maven资源插件。因此,在如此晚的阶段向构建中添加更多资源只会产生装饰效果,例如Eclipse 等 IDE 将 generated-resources 文件夹识别为源文件夹并相应地标记它。

您必须手动将结果从您的插件复制到构建输出文件夹:

import org.codehaus.plexus.util.FileUtils;

// Finally, copy all the generated resources over to the build output folder because
// we run after the "process-resources" phase and Maven no longer handles the copying
// itself in later phases.
try {
    FileUtils.copyDirectoryStructure(
            new File("target/generated-resources/some"),
            new File(project.getBuild().getOutputDirectory()));
}
catch (IOException e) {
    throw new MojoExecutionException("Unable to copy generated resources to build output folder", e);
}