春季问题:无法列出具有 @CustomAnnotation 的属性

时间:2021-02-26 22:58:09

标签: java spring spring-boot annotations

项目启动时,想法是搜索所有带有@AppProperty注解的de变量。

测试,我无法得到列表,总是得到一个空列表。我正在使用 ApplicationContext 中的 getBeansWithAnnotation () 函数。我的理论是,在执行搜索时,它们尚未加载,但我无法确认是这样。

这里是项目的开始,我在项目解除后使用@EventListener运行。

Beggining Image

在那里调用 ApplicationPropertyService,我尝试获取包含@AppProperty 注释的所有属性的列表

Service Image

这是我想要显示给我的两个属性。

public interface ApplicationProperties {

    @AppProperty( key = "version" , value ="1.0.0" , active = true)
    public String APP_VERSION = "version";
    
    @AppProperty( key = "checkVersion" , value = "true" , active = true)
    public String APP_CHECK_VERSION = "checkVersion";
    
}

@注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AppProperty {

    String key();
    
    String value() default "";
    
    boolean active() default false;
    
}

1 个答案:

答案 0 :(得分:1)

我认为您的代码中有几个问题。

首先,正如您在 getBeansWithAnnotation 方法 documentation 中看到的那样,它只会检测级别的注释:

<块引用>

查找 Class 具有提供的 Annotation 类型的所有 bean,返回一个带有相应 bean 实例的 bean 名称映射。

但是,您正在尝试将它们应用于仅对字段进行注释的类,并且定义了仅适用于字段级别的注释 - 根据 @Target(ElementType.FIELD) - 注释。

您应该创建一个适用于类型 @Target(ElementType.TYPE) 的新注解,并使用这个新注解应用 Spring 需要识别的类。

此外,该类(在您的示例中为 ApplicationProperties)应该用允许 Spring 找到它的内容进行注释。例如,您可以使用 @Component@Service 等,或者您可以定义 ...) 或将 ApplicationProperties 定义为应用程序上下文中某处的 @Bean:{ {1}} 只会向您提供有关 Spring beans 的信息。

最后,Spring 提供了一个基于 getBeansWithAnnotation 抽象和相关内容的开箱即用的功能丰富的基于属性的配置系统。请查看 reference guide,它提供了大量有关此主题的信息。