在maven编译中替换源文件

Mar*_*rko 3 maven-2

maven compile如果特殊配置文件处于活动状态,我必须替换Java源文件.我想过只是从标准中排除文件,src/main/java/并将其包含在另一个源目录中src/main/java2/.

但由于文件必须具有相同的名称和包,因此排除总是获胜,而其他目录中的文件永远不会被包含在内......

任何已知的工作方式吗?

Pas*_*ent 5

我会使用Maven Antrun插件重命名"原始"源文件,并将"特殊"源文件从相位之前复制src/main/java2到.之后,恢复原始源文件.这样的东西(把它放在配置文件中):src/main/javacompilecompile

<plugin>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.4</version>
  <executions>
    <execution>
      <id>replace-source-file</id>
      <phase>process-sources</phase>
      <configuration>
        <tasks>
          <move file="src/main/java/com/stackoverflow/App.java" tofile="src/main/java/com/stackoverflow/App.java.moved"/>
          <copy file="src/main/java2/com/stackoverflow/App.java" todir="src/main/java/com/stackoverflow/"/>
        </tasks>
      </configuration>
      <goals>
        <goal>run</goal>
      </goals>
    </execution>
    <execution>
      <id>restore-source-file</id>
      <phase>compile</phase>
      <configuration>
        <tasks>
          <move file="src/main/java/com/stackoverflow/App.java.moved" tofile="src/main/java/com/stackoverflow/App.java"/>
        </tasks>
      </configuration>
      <goals>
        <goal>run</goal>
      </goals>
    </execution>
  </executions>
</plugin>
Run Code Online (Sandbox Code Playgroud)

更新:正如OP在评论中所提到的,这种方法存在一个主要缺点.如果存在编译错误,则错误的源文件(和*.java.moved文件)将保留在src/main/java目录中.这是个问题.

更清晰的替代方案是在专用模块中移动源的两个版本,并根据配置文件将一个或另一个模块声明为依赖项(默认情况下,正常工件将包含在活动配置文件中).我甚至不会搞乱编译器排除.这样可行并且干净.