@ComponentScan注释适用于非@Configuration类

时间:2018-11-28 20:33:51

标签: java spring spring-ioc

Spring参考文档中的内容如下:

  

Spring可以自动检测构造型类并向ApplicationContext注册相应的BeanDefinition实例...

     

要自动检测这些类并注册相应的bean,您需要将@ComponentScan添加到您的@Configuration类中...

我创建了一个简单的示例来测试Spring框架的自动检测功能:

/**
 * Java-based configuration class which defines root package to start scanning from.
 */
@ComponentScan
public class ComponentScanPackageMarker {
}

/**
 * Class annotated with <b>stereotype</b> annotation is a candidate for automatic detection and registering as
 * {@link BeanDefinition} instance.
 */
@Component
public class Pen {

    private Ink ink;

    @Autowired
    public Pen(Ink ink) {
        this.ink = ink;
    }
}

/**
 * Auto-detected class which will be used as auto-wiring candidate for another auto-detected component.
 */
@Component
public class Ink {
}
对于 ComponentScanPackageMarker 类,故意省略了

@Configuration批注。我已经测试了组件扫描和自动装配功能。令我惊讶的是,一切进展顺利:

@Test
public void shouldAutoDetectAndRegisterBeans() {
    try (AnnotationConfigApplicationContext context =
                 new AnnotationConfigApplicationContext(ComponentScanPackageMarker.class)) {
        Pen pen = context.getBean(Pen.class);
        Assert.assertNotNull(pen);
        Ink ink = context.getBean(Ink.class);
        Assert.assertNotNull(ink);
    }
}

这种组件扫描的行为是故意的吗?为什么即使没有@Configuration批注也能正常工作?

1 个答案:

答案 0 :(得分:0)

是的。 我认为@ComponentScan的工作是扫描给定的程序包并注册带有构造型注释(@ Component,@ Configuration,@ Service,@ Repository)的Bean(如果发现),而@Configuration的工作是注册方法的(带有@Bean的注释)返回值作为容器中的bean。

如果我错了,请纠正我。