【问题标题】:Maven compiler, only compile annotated classesMaven 编译器,只编译带注解的类
【发布时间】:2014-01-07 10:36:39
【问题描述】:

我在我正在处理的 Maven 2 项目中创建了一个自定义 Java 注释(代码如下):

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MYANNOTATION{}

在 Maven 构建的一部分中,我只想编译带有此注释的类,例如:

@MYANNOTATION
public class MyClass {
    // Code here
}

我目前使用Maven Compiler Plugin 来限制基于包结构的复杂性。我的 pom.xml 包含类似于下面的一个,将编译限制为 **com.foo.bar.stuff** 和 **com.baz.foo.more** 中的类。这是不满意的,因为当我在com.xyz.bar.foo 中添加注解的类时,我必须记得在pom 中定义它。

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <executions>
          <execution>
            <id>default-compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <includes>
                <include>**/com/foo/bar/stuff/**</include>
                <include>**/com/baz/foo/more/**</include>
              </includes>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

有没有什么方法可以定义 Maven 只编译已使用此注解的类,而不取决于它们在包层次结构中的位置?

(我正在尝试从域模型类生成元模型,这样我就可以指向字段和方法,而无需将名称定义为字符串常量 - 并在我重构时手动更改它们)

编辑:我已经在构建阶段的另一部分进行注释处理。系统是这样工作的:

  1. 编译指定包中的类
  2. 使用JAnnocessor,从带有@MYANNOTATION 的类构建元模型
  3. 编译其余的类

从其他类到元模型类的依赖关系会阻止一次编译所有内容,除非我们将带注释的类移动到不同的项目并为其添加依赖关系。这是一种可能性,但会增加复杂性,因为当前的项目结构似乎形成了一个合乎逻辑的整体。

【问题讨论】:

  • 注解处理器将对具有请求注解的类执行处理,但编译器需要首先解析源代码,以便找到注解。我能看到将编译器的 java 文件输入集限制为仅具有一组注释的文件的唯一方法是通过 grep 之类的东西对整个源文件集(也许可以在此处使用 ant 插件)。但即便如此,编译器也会加载引用的类,你最终可能会解析整个源代码树。

标签: java maven maven-2 annotations maven-compiler-plugin


【解决方案1】:

您可以通过注释处理执行与您想要的类似的操作。我认为您不需要做任何特定于 maven 的事情,但您需要编写一个注释处理器,该处理器必须是单独库的一部分或单独编译。

注释处理的概念在这篇博文中有很好的解释:

Code Generation using Annotation Processors in the Java language – part 2: Annotation Processors

【讨论】:

    猜你喜欢
    • 2012-06-08
    • 1970-01-01
    • 2013-12-03
    • 2013-06-29
    • 2013-03-07
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-03
    相关资源
    最近更新 更多