2

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?

Laplas
  • 687
  • 1
  • 7
  • 10
  • Are you using Spring Boot? – Makoto Nov 28 '18 at 20:36
  • 2
    By providing `ComponentScanPackageMarker.class` as an argument to that constructor, it essentially acts as if it was a `@Configuration` annotated class. – Sotirios Delimanolis Nov 28 '18 at 20:39
  • @Makito I'm using plain Spring v5.1. – Laplas Nov 28 '18 at 20:40
  • @SotiriosDelimanolis As it seems, `AnnotationConfigApplicationContext` class doesn't validate arguments passed to the constructor in any way... even plain POJOs are okay to be passed. Thanks for guiding in the right direction. – Laplas Nov 28 '18 at 20:57

1 Answers1

1

Yes. I think the job of @ComponentScan is to scan given packages and register beans annotated with Stereotype annotations (@Component, @Configuration, @Service, @Repository) if found any while job of @Configuration is to register method's (annotated with @Bean) return value as a bean in the container.

Correct me if I am wrong.

Mahesh Bhuva
  • 744
  • 5
  • 17
  • 1
    Yes you're right, just was confused that Spring reference documentation doesn't say about this clearly and suggests to use `@ComponentScan` annotation along with `@Configuration` annotation. – Laplas Dec 02 '18 at 15:37