如何在不使用@Component注释注释的情况下告诉Spring扫描给定的注释?

时间:2018-02-26 13:12:45

标签: java spring spring-boot dependency-injection

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

但是,@ MyAnnotation构成了我项目的API的一部分,我不想在Spring上声明这个API的显式依赖。因此,我不能用@Component注释@MyAnnotation,以便Spring可以传递它。

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

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

提前致谢。

2 个答案:

答案 0 :(得分:3)

如果您创建自己的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");

在此示例中,它将在@Foo包中找到所有使用com.example.my注释的类。

答案 1 :(得分:0)

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

但要让你的@MyAnnotation更加困难(请参阅@ g00glen00b的回答),如果上述解决方案可用,我不确定是否有意义。