【问题标题】:ComponentScan does not find own custom annotations after update from Spring Boot 2.0.3 to 2.2.4从 Spring Boot 2.0.3 更新到 2.2.4 后,ComponentScan 找不到自己的自定义注解
【发布时间】:2020-05-27 19:28:24
【问题描述】:

在从 Spring Boot 2.0.3 更新到 2.2.4 之前,我们有一些注释,如下例所示:

import org.springframework.stereotype.Component;

@Component
public @interface Adapter {
}

在 ComponentScan 期间,使用此 Adapter 注释注释的类被拾取并添加到 Spring 上下文中。更新后有org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'XY' available

根据Spring Annotation Programming Model 术语中关于刻板印象注释的一段话,我们的方法应该有效:

任何带有@Component 注解的组件都是组件扫描的候选对象。类似地,任何使用注解注解且本身使用@Component 元注解的组件也是组件扫描的候选对象。

我阅读了 Spring Boot 2.1 和 2.2 的发行说明以及 Spring Framework 5.1 和 5.2 的发行说明,但没有发现构造型注释的行为在这一点上发生了变化。

当我使用 Spring 提供的原型注释(除了我们自己的注释)来注释类时,它们会被 ComponentScan 拾取。

我还尝试像这样在@ComponentScan 中设置自定义过滤器

@ComponentScan(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION,
    classes = Adapter.class))

但仍然得到NoSuchBeanDefinitionException

最后我在 Spring Framework 中偶然发现了这个 "Enhancement",想知道这是否是我问题的根源。

所以到目前为止没有任何效果,如果有人能指出我的方向来恢复我们自己的刻板印象注释再次起作用的原始行为,我会很高兴。提前致谢。

【问题讨论】:

    标签: spring spring-boot migration spring-annotations component-scan


    【解决方案1】:

    在仔细查看 Spring Stereotype 注释后,在我们的注释中添加 @Retention(RetentionPolicy.RUNTIME) 解决了这个问题。带有我们自己注释的类会再次被 ComponentScan 拾取。

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    import org.springframework.stereotype.Component;
    
    @Retention(RetentionPolicy.RUNTIME)
    @Component
    public @interface Adapter {
    }
    

    【讨论】:

    • 我在这个问题上遇到了很多困难(从和升级到确切的版本),这是一个宝贵的提醒,要始终查看实现。不过,在您的Adapter 上,我相信不需要Component
    猜你喜欢
    • 1970-01-01
    • 2020-12-21
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多