【发布时间】:2026-02-25 00:45:02
【问题描述】:
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 注解也能正常工作?
【问题讨论】:
-
你在使用 Spring Boot 吗?
-
通过将
ComponentScanPackageMarker.class作为参数提供给该构造函数,它实际上就像是一个@Configuration注释类。 -
@Makito 我使用的是纯 Spring v5.1。
-
@SotiriosDelimanolis 看起来,
AnnotationConfigApplicationContext类不会以任何方式验证传递给构造函数的参数......即使是普通的 POJO 也可以传递。感谢您指导正确的方向。
标签: java spring spring-ioc