maven 无法在编译阶段的生成源中添加文件

问题描述 投票:0回答:3

我使用 Apache Thrift

target/generated-sources
中生成代码。

Thrift 编译器生成一个名为

gen-java
的目录,其中包含所有 Java 代码。当我执行
mvn compile
时,代码在
target/generated-source/gen-java
中正确生成,但在编译阶段,它抱怨找不到
gen-java
中定义的类。

根据我的理解,Maven 2 会自动添加生成的源,对吗?

如果我的测试代码也依赖于

generated-sources
,我是否必须手动指定编译器包含的内容?

maven code-generation thrift
3个回答
22
投票

按照我的理解,maven 2会自动添加生成的源,对吗?

没有什么是自动的,生成源代码的插件通常通过将其输出目录(按照惯例类似于

target/generated-sources/<tool>
)作为源目录添加到 POM 来处理该问题,以便稍后在编译阶段将其包含在内。

一些实施得不太好的插件无法为您执行此操作,您必须自己添加目录,例如使用 Build Helper Maven Plugin

由于您没有提供任何 POM 片段、任何链接,我不能再说什么了。

如果我的测试代码也依赖于生成的源代码,我是否必须手动指定编译器包含的内容?

正如我所说,生成的源通常作为源目录添加并编译,因此无需执行任何操作即可在测试类路径上使用。


6
投票

生成的源代码不会自动编译或打包。然而,某些 IDE(即 IntelliJ)会将它们显示为源文件夹。

要使生成的源对 Maven 可见,请将

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>

0
投票

在我的例子中,生成的模型是使用脚本的外部流程的一部分。

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>
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.