How to exclude java classes from being compiled in maven with annotation

ε祈祈猫儿з 提交于 2021-02-09 02:47:59

问题


I already have a working solution where I can specify with maven which classes to not compile when using a particular maven profile.

But I would like to use a general solution and use an annotation instead

The current solution that I have is like

<plugin>
    <!-- Exclude some web services used only for internal testing -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <optimize>true</optimize>
        <excludes>
            <exclude>**/something/*ClassPattern.java</exclude>
        </excludes>
        <testExcludes>
            <exclude>**/something/*ClassPatternTest.java</exclude>
        </testExcludes>
    </configuration>
</plugin>

But Some thing like

@NotCompiledForProduction 

would be rather nice on top of a class.

It seems to me that this might be hard (or impossible to do) without changing maven's behaviour. That is not the scope here. And this kind of annotation


回答1:


you can try this...

<build> <plugins>
  <!-- Run annotation processors on src/main/java sources -->
  <plugin>
    <groupId>org.bsc.maven</groupId>
    <artifactId>maven-processor-plugin</artifactId>
    <executions>
      <execution>
        <id>process</id>
        <goals>
          <goal>process</goal>
        </goals>
        <phase>generate-sources</phase>
      </execution>
    </executions>
  </plugin>
  <!-- Disable annotation processors during normal compilation -->
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <compilerArgument>-proc:none</compilerArgument>
    </configuration>
  </plugin>
</plugins> </build>



回答2:


You cannot (I assume) use an annotation to determine what source code gets presented to the java compiler, because you need to compile the source code in the first place to process the annotation.

It seems like you need to create different modules in your maven project: one that generates a jar file with the production code, and one module that generates a jar file with testing implementation with a dependency on the production artifact.

If the code really does need to be in the same maven module, then the code should always be compiled. You can however use maven-jar-plugin to create multiple artifacts at the package phase: the default artifactId.jar, and an artifactId-test-lib.jar artifact. You can do this by specifying multiple executions for the plugin, and using <includes> and <excludes> to split the jar files as required.



来源:https://stackoverflow.com/questions/14939276/how-to-exclude-java-classes-from-being-compiled-in-maven-with-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!