【问题标题】:How can I tell Spring to scan for a given annotation without annotating that annotation with @Component?如何告诉 Spring 扫描给定的注释而不用 @Component 注释该注释?
【发布时间】:2018-08-05 23:05:07
【问题描述】:

我有一组要注入到 Spring 应用程序上下文中的类。但是,这些类只能保证使用我编写的一组注释中的一个进行注释 - 即我可以假设它将使用 @MyAnnotation 进行注释,而不是 @Component。

但是,@MyAnnotation 构成了我项目的 API 的一部分,我不想声明此 API 对 Spring 的显式依赖。因此,我不能用 @Component 注释 @MyAnnotation 以使其被 Spring 传递地拾取。

有没有办法告诉 Spring 在其类路径扫描中额外包含 @MyAnnotation 而不将此依赖项添加到我的 API?

目前我正在操作 bean 定义注册表以“手动”添加每个使用 @MyAnnotation 注释的类,但我更愿意依赖 Spring 的内置支持。

提前致谢。

【问题讨论】:

  • 您是否已经使用 BeanDefinationProcessor 手动将它们加载到上下文中?

标签: java spring spring-boot dependency-injection


【解决方案1】:

@Configuration 类和基于 XML 的配置应该适合您。看看这个教程:https://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

但是要让您的@MyAnnotations 被接走更加困难(请参阅@g00glen00b 的回答),我不确定上述解决方案是否可用。

【讨论】:

  • 类似于无法控制 @Component 是否添加到我希望被选中的给定类中,我也无法控制类是否包装在 @987654325 中的 bean 方法中@ 班级。用@MyAnnotation 注释的类是由我的图书馆的消费者编写的。我可以保证它将用@MyAnnotation 进行注释,但消费者不应该自己编写方法来将类添加到应用程序上下文中。这应该由@MyAnnotation 透明地处理。
【解决方案2】:

如果您创建自己的BeanDefinitionRegistryPostProcessor 来注册您自己的bean,这是可能的。如果你实现了postProcessBeanDefinitionRegistry方法,你可以自己将bean添加到注册表中,例如:

@Component
public class FooFactoryBean implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        registry.registerBeanDefinition(..);
    }
}

要获得这些 bean 定义,您可以使用 ClassPathScanningCandidateComponentProvider 类,该类将为为特定过滤器找到的所有类创建 BeanDefinition 对象。在这种情况下,AnnotationTypeFilter 将起作用:

ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(Foo.class));
Set<BeanDefinition> definitions = scanner.findCandidateComponents("com.example.my");

在本例中,它将在com.example.my 包中找到所有带有@Foo 注释的类。

【讨论】:

    猜你喜欢
    • 2015-02-17
    • 2012-10-19
    • 1970-01-01
    • 2017-05-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 2021-08-10
    相关资源
    最近更新 更多