我使用 Apache Thrift 在
target/generated-sources
中生成代码。
Thrift 编译器生成一个名为
gen-java
的目录,其中包含所有 Java 代码。当我执行mvn compile
时,代码在target/generated-source/gen-java
中正确生成,但在编译阶段,它抱怨找不到gen-java
中定义的类。
根据我的理解,Maven 2 会自动添加生成的源,对吗?
如果我的测试代码也依赖于
generated-sources
,我是否必须手动指定编译器包含的内容?
按照我的理解,maven 2会自动添加生成的源,对吗?
没有什么是自动的,生成源代码的插件通常通过将其输出目录(按照惯例类似于
target/generated-sources/<tool>
)作为源目录添加到 POM 来处理该问题,以便稍后在编译阶段将其包含在内。
一些实施得不太好的插件无法为您执行此操作,您必须自己添加目录,例如使用 Build Helper Maven Plugin。
由于您没有提供任何 POM 片段、任何链接,我不能再说什么了。
如果我的测试代码也依赖于生成的源代码,我是否必须手动指定编译器包含的内容?
正如我所说,生成的源通常作为源目录添加并编译,因此无需执行任何操作即可在测试类路径上使用。
生成的源代码不会自动编译或打包。然而,某些 IDE(即 IntelliJ)会将它们显示为源文件夹。
add-source
步骤添加到 build/plugins
的 pom.xml
节点:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources/gen-java</source><!-- adjust folder name to your needs -->
</sources>
</configuration>
</execution>
</executions>
</plugin>
在我的例子中,生成的模型是使用脚本的外部流程的一部分。
asyncapi generate models java ${{github.workspace}}/src/main/resources/asyncAPI-Swagger.yaml \
--packageName=com.example.asyncapi.model \
-o=src/gen/java/com/example/asyncapi/model \
--javaJackson --javaConstraints --javaArrayType=List \
需要将其添加到源根目录中,以便对其进行编译并可用于捆绑应用程序或执行测试
下面 pom.xml 中的插件配置添加了
src/gen
以及默认的 src/main
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.5.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/</source>
<source>src/gen/</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>