Stefano Sambruna
Stefano Sambruna

Reputation: 797

Must @ComponentScan be placed with @Configuration? (Spring Core)

I read inside many articles that @ComponentScan should be placed with @Configuration on top of a class. Here some references:

we use the @ComponentScan annotation along with @Configuration annotation to specify the packages that we want to be scanned (https://www.baeldung.com/spring-component-scanning)

@ComponentScan(basePackages = "com.zetcode") @Configuration public class Application { ... } (http://zetcode.com/spring/componentscan)

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. (https://dzone.com/articles/spring-component-scan)

I was curious to try if without @Configuration an exception would have been thrown. Surprisingly everything works fine even without @Configuration. Here the code:

@ComponentScan
public class AppConfig {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
    }
}

I had just one sample bean which got printed.

@Component
public class Car {

}

This was the output of the main method:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
appConfig
car

Why does it work? and why do they tell to use it with configuration? was it an old requirement?

And even more surprisingly appConfig becomes a bean, even if it does not have any particular annotation such as @Configuration or @Component. So does that mean that anything that gets put as argument of new AnnotationConfigApplicationContext() gets turned into a bean no matter what annotation does it has or has not?

I probably miss some core spring behavior which would justify this. Any idea?

Upvotes: 3

Views: 731

Answers (1)

You are still using @Configuration together with @ComponentScan implicitly. By pasing the AppConfig.class as param to the context, it considers it configuration. That would explain the bean created for it as well

Upvotes: 2

Related Questions