简体   繁体   English

自定义注释的 Intellij 代码检查

[英]Intellij Code Inspection for Custom Annotation

One of the problems I've encountered while using DTOs is that I often find myself shipping (accidentally) entities along with DTOs.我在使用 DTO 时遇到的问题之一是,我经常发现自己(意外地)将实体与 DTO 一起发送。 To mitigate this problem, I created another Maven project with an annotation (@ValidDTO) and its processor that finds if a DTO annotated with @ValidDTO has @Entity annotated fields.为了缓解这个问题,我创建了另一个带有注释 (@ValidDTO) 的 Maven 项目及其处理器,用于查找使用 @ValidDTO 注释的 DTO 是否具有 @Entity 注释字段。

This is my annotation.这是我的注释。

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface ValidDTO {}

And, this is my processor.而且,这是我的处理器。

@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;
    }
}

This is how my POM.xml looks for the Maven project with the annotation and its processor这就是我的 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>

So, I installed this package as a dependency in another projected and annotated a DTO with it.因此,我将此包作为依赖项安装在另一个投影中,并用它注释了 DTO。 I purposefully added couple of entities as member variables to see the error.我特意添加了几个实体作为成员变量来查看错误。

@ValidDTO
public class FacilityDTO {
  private User user;
  private List<User> users;
}

where,在哪里,

@Entity
@Table("User")
public class User {} 

is an entity.是一个实体。

Now, my custom annotation works perfectly good when I run mvn clean install or build project.现在,当我运行mvn clean install或 build 项目时,我的自定义注释工作得非常好。 I can see the expected "Types annotated with ValidDTO cannot have member variables that are @Entity annotated" in the terminal.我可以在终端中看到预期的"Types annotated with ValidDTO cannot have member variables that are @Entity annotated"

However, I do not see the error in the editor of the IDE.但是,我在 IDE 的编辑器中没有看到错误。 I've tried both Intellij and Eclipse and I do not see any red squiggly line underneath the annotation telling me that the DTO is invalid.我已经尝试了 Intellij 和 Eclipse,但在注释下方没有看到任何红色波浪线告诉我 DTO 无效。

The closest expected desired behavior I can reference is a compile error when using @FunctionalInterface on an interface that has more than one abstract method.我可以引用的最接近的预期行为是在具有多个抽象方法的接口上使用@FunctionalInterface时的编译错误。

I just need help configuring my IDE.我只需要帮助配置我的 IDE。 Any help is appreciated!任何帮助表示赞赏!

In IntelliJ you can create custom inspections.在 IntelliJ 中,您可以创建自定义检查。 These can be used to alert you to the presence of custom search patterns in your code ( https://www.jetbrains.com/help/idea/creating-custom-inspections.html ).这些可用于提醒您代码中存在自定义搜索模式 ( https://www.jetbrains.com/help/idea/creating-custom-inspections.html )。

For your case: Go to settings -> Editor -> Inspections.对于您的情况:转到设置 -> 编辑器 -> 检查。 Activate "Structural search inspection" and add a "Search Template":激活“结构搜索检查”并添加“搜索模板”:

在此处输入图片说明

(UPDATE 06/2020: "Structural search" is not under "General" anymore but is now a separate topic) (更新 06/2020:“结构搜索”不再属于“常规”,但现在是一个单独的主题)

Add following structural search:添加以下结构搜索:

在此处输入图片说明

You may change "Severity" to "Error" to get the red squiggly lines.您可以将“严重性”更改为“错误”以获得红色波浪线。 :) :)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM