在本教程中,我们将解释如何在Spring中查找所有带有自定义注解的Bean。我们将展示根据不同的Spring版本使用的不同方法。
2. 使用Spring Boot 2.2或更高版本
自Spring Boot 2.2以来,我们可以使用getBeansWithAnnotation方法。
让我们构建一个示例。首先,我们将定义我们的自定义注解。我们将使用@Retention(RetentionPolicy.RUNTIME)对其进行注解,以确保程序在运行时可以访问该注解:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
}
大约 4 分钟