【发布时间】:2020-07-03 13:28:23
【问题描述】:
我在使用 DTO 时遇到的一个问题是,我经常发现自己(意外地)随 DTO 一起运送实体。为了缓解这个问题,我创建了另一个带有注解 (@ValidDTO) 的 Maven 项目,它的处理器会查找使用 @ValidDTO 进行注解的 DTO 是否具有带有 @Entity 注解的字段。
这是我的注释。
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface ValidDTO {}
而且,这是我的处理器。
@SupportedAnnotationTypes("com.aj.annotations.ValidDTO")
@SupportedSourceVersion(SourceVersion.RELEASE_11)
public class ValidDTOProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> set,
RoundEnvironment roundEnv) {
List<Entity> entityFields = roundEnv.getElementsAnnotatedWith(ValidDTO.class)
.stream()
.filter(element -> element.getKind()==ElementKind.CLASS || element.getKind()==ElementKind.INTERFACE)
.map(Element::getEnclosedElements)
.flatMap(List::stream)
.filter(element -> element.getKind()==ElementKind.FIELD)
.map(element -> element.getAnnotation(Entity.class))
.collect(Collectors.toList());
if (!entityFields.isEmpty()) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Types annotated with ValidDTO " +
"cannot have member variables that are @Entity annotated");
}
return true;
}
}
这就是我的 POM.xml 查找带有注解及其处理器的 Maven 项目的方式
<groupId>com.aj</groupId>
<artifactId>aj-annotations</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
<generatedSourcesDirectory>${project.build.directory}/generated-sources/
</generatedSourcesDirectory>
<proc>none</proc>
<annotationProcessors>
<annotationProcessor>
com.aj.annotations.processors.ValidDTOProcessor
</annotationProcessor>
</annotationProcessors>
<debug>true</debug>
</configuration>
</plugin>
</plugins>
</build>
因此,我将此包作为依赖项安装在另一个投影中并用它注释了 DTO。我特意添加了几个实体作为成员变量来查看错误。
@ValidDTO
public class FacilityDTO {
private User user;
private List<User> users;
}
在哪里,
@Entity
@Table("User")
public class User {}
是一个实体。
现在,当我运行mvn clean install 或构建项目时,我的自定义注释工作得非常好。我可以在终端中看到预期的"Types annotated with ValidDTO cannot have member variables that are @Entity annotated"。
但是,我在 IDE 的编辑器中没有看到错误。我已经尝试过 Intellij 和 Eclipse,但在注释下方没有看到任何红色波浪线告诉我 DTO 无效。
在具有多个抽象方法的接口上使用 @FunctionalInterface 时,我可以引用的最接近预期的期望行为是编译错误。
我只需要帮助配置我的 IDE。任何帮助表示赞赏!
【问题讨论】:
标签: java maven intellij-idea annotations annotation-processing