我知道这个问题并不新鲜。但是似乎没有确定的答案。 2012年的This answer指出,如果将生成的源放置在target/generated-sources/<tool>
下,则将对其进行编译。 ANTLR 4 maven plugin遵循此范例。根据文档,outputDirectory的默认值为:${project.build.directory}/generated-sources/antlr4
。
就我而言,我有一个自定义工具可以生成源。我已将其输出目录设置为${project.build.directory}/generated-sources/whatever
,但该目录不起作用。关于whatever
部分,我尝试使用生成源的目标ID,甚至尝试劫持antlr4
名称。虽然没有结果。
[当我尝试this solution时建议使用mojo build-helper-maven-plugin
,它将按预期编译。但是根据maven guide to generating sources,它应该在没有任何帮助程序插件的情况下工作,不是吗?我想念什么吗?
这是我用来生成源的POM(片段)配置。
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>generate-code</id>
<phase>generate-sources</phase>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<includeProjectDependencies>false</includeProjectDependencies>
<includePluginDependencies>true</includePluginDependencies>
<executableDependency>
<groupId>com.company.product</groupId>
<artifactId>CodeGenerator</artifactId>
</executableDependency>
<arguments>
<argument>${basedir}/</argument>
<argument>${project.build.directory}/generated-sources/generate-code/</argument>
</arguments>
<mainClass>com.company.codegeneration.CodeGenerator</mainClass>
</configuration>
<dependencies>
<dependency>
<groupId>com.company.product</groupId>
<artifactId>CodeGenerator</artifactId>
<version>1.0-SNAPSHOT</version>
<type>jar</type>
</dependency>
</dependencies>
</plugin>
您的理解有点不正确。
没有什么自动的,生成插件的源代码通常通过添加其输出目录来处理该问题(类似于target / generate-sources /按照惯例)作为POM的源目录,以便稍后在编译阶段将其包括在内。
一些实施不完善的插件无法为您做到这一点,而您拥有自己添加目录,例如使用构建助手Maven插件。
如另一个答案所述,大多数插件通常将生成的代码添加为新的源路径。
Ex:请参阅antlr4's Antlr4Mojo.java类。在这里,该插件通过在addSourceRoot
方法中调用execute
方法,将生成的类添加到项目源中。
// Omitted some code void addSourceRoot(File outputDir) { if (generateTestSources) { project.addTestCompileSourceRoot(outputDir.getPath()); } else { project.addCompileSourceRoot(outputDir.getPath()); } } // Omitted some code @Override public void execute() throws MojoExecutionException, MojoFailureException { // Omitted code if(project!=null) { // Tell Maven that there are some new source files underneath the output // directory. addSourceRoot(this.getOutputDirectory()); } } // Omitted some code
因此,您可以在您的自定义插件中执行此操作,也可以使用
build-helper-maven-plugin
。