Spring reference documentation says the following:
Spring can automatically detect stereotyped classes and register corresponding BeanDefinition instances with the ApplicationContext ...
To autodetect these classes and register the corresponding beans, you need to add @ComponentScan to your @Configuration class ...
I've created a simple example to test auto-detection functionality of Spring framework:
/**
* 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 {
}
@Configuration annotation was intentionally omitted for ComponentScanPackageMarker class. I've tested component scanning and autowiring functionality. To my surprise everything went well:
@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);
}
}
Is this behavior of component-scanning intentional? Why does it work even without @Configuration annotation?