You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Maven模板引擎项目:编译测试生成类及打包示例类的方案咨询

解决方案

一、直接在核心模块实现编译与测试

完全可以在myproject-core模块内完成生成类的编译和专用测试,不需要额外模块,借助Maven的几个核心插件就能搞定:

1. 固定生成类的输出目录

先确保你的FreeMarker引擎把生成的Java类输出到Maven标准的生成源码目录,比如target/generated-sources/freemarker,方便后续插件识别。

2. 把生成目录注册为源码路径

用build-helper-maven-plugin将生成目录添加到Maven的源码集合中,这样maven-compiler-plugin会自动编译这些类:

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>build-helper-maven-plugin</artifactId>
      <version>3.4.0</version>
      <executions>
        <execution>
          <id>add-generated-sources</id>
          <phase>generate-sources</phase>
          <goals>
            <goal>add-source</goal>
          </goals>
          <configuration>
            <sources>
              <source>${project.build.directory}/generated-sources/freemarker</source>
            </sources>
          </configuration>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

3. 编写专用测试类验证

在src/test/java下创建专门的测试类,直接引用编译后的生成类即可,比如:

public class GeneratedClassValidationTest {
    @Test
    public void testBasicFunctionality() {
        GeneratedUser user = new GeneratedUser();
        user.setUsername("test");
        assertEquals("test", user.getUsername());
        // 其他业务逻辑验证
    }
}

执行mvn test时,Maven会先完成生成类的编译,再自动运行这些测试用例。

二、是否需要单独测试模块?

不是必须的,但如果你的测试逻辑非常复杂(比如涉及多场景集成、需要额外依赖),或者不想让生成类的编译逻辑污染核心模块的构建流程,可以单独创建myproject-test模块:

  • 让测试模块依赖myproject-core
  • 在测试模块内调用核心引擎生成类,重复上述编译配置,再编写测试用例
    这种拆分适合大型项目,结构更清晰;小型项目直接在核心模块处理更高效。

三、将生成类作为示例打包

完全可以把生成的类(或源码)作为示例打包到项目中,两种常用方式:

1. 把生成源码打包进主Jar

用maven-resources-plugin把生成的源码复制到Jar包的指定目录(比如examples),打包时会自动包含:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-resources-plugin</artifactId>
  <version>3.3.1</version>
  <executions>
    <execution>
      <id>copy-examples</id>
      <phase>process-resources</phase>
      <goals>
        <goal>copy-resources</goal>
      </goals>
      <configuration>
        <outputDirectory>${project.build.outputDirectory}/examples</outputDirectory>
        <resources>
          <resource>
            <directory>${project.build.directory}/generated-sources/freemarker</directory>
            <includes>
              <include>**/*.java</include>
            </includes>
          </resource>
        </resources>
      </configuration>
    </execution>
  </executions>
</plugin>

2. 单独打包示例包

如果想把示例做成独立的Jar包,用maven-assembly-plugin配置专门的描述文件,生成myproject-examples.jar,和主Jar一起发布即可。

内容的提问来源于stack exchange,提问作者Yoshi31

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:12:13