在Maven中替换源文件进行编译

在Maven中替换源文件进行编译

本文介绍了在Maven中替换源文件进行编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果特殊配置文件处于活动状态,则必须在maven compile期间替换Java源文件.我考虑过只从标准src/main/java/中排除文件,并从src/main/java2/等另一个源目录中包括它.

I have to replace a Java source file during maven compile if a special profile is active.I thought about just excluding the file from the standard src/main/java/ and including it from another source directory like src/main/java2/.

但是由于文件必须具有相同的名称和程序包,所以排除总是会获胜,而另一个目录中的文件将永远不会被包含在内...

But since the files have to have the same name and package the exclude always wins and the file from the other directory gets never included...

有什么已知的工作方式吗?

Any known working way to do that?

推荐答案

我会使用 Maven Antrun插件重命名原始"源文件,并在compile阶段之前将特殊"源文件从src/main/java2复制到src/main/java. compile之后,还原原始源文件.这样的事情(在个人资料中输入):

I would use the Maven Antrun Plugin to rename the "original" source file and copy the "special" source file from src/main/java2 to src/main/java before the compile phase. After compile, restore the original source file. Something like that (put that in the profile):

<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>

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

Update: As mentioned by the OP in a comment, there is a major drawback with this approach. If there is a compile error the wrong source file (and the *.java.moved file) stays in the src/main/java directory. This is a problem.

更清洁的选择是将源的两个版本都移到专用模块中,并根据配置文件将一个或另一个模块声明为依赖项( normal 工件将包含在活动配置文件中)默认情况下).我什至不会把编译器排除在外.这将工作,很干净.

A cleaner alternative would be to move both versions of the source in dedicated modules and to declare one or the other module as dependency depending on the profile (the normal artifact would be included in a profile active by default). I wouldn't even mess with compiler exclusions. This would work and is clean.

这篇关于在Maven中替换源文件进行编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:06