varunkr varunkr - 2 months ago 14
Java Question

Why is a bean declared in @SpringBootApplication class registered even though it is not a stereotyped class?

I have this main class in my project

@SpringBootApplication
@EnableOAuth2Sso
public class App
{
public static void main(String[] args) throws Exception {
SpringApplication.run(App.class, args);
}

@Bean public RequestContextListener requestContextListener(){
return new RequestContextListener();
}

}


As far as I know, component scan scans beans in stereotyped classes which are one of
@Component, @Service, @Repository, @Controller
if I am not wrong.

From spring docs


By default, classes annotated with @Component, @Repository, @Service,
@Controller, or a custom annotation that itself is annotated with
@Component are the only detected candidate components.


I cannot understand how the bean in this class is registered. As it is not a stereotyped class and no annotation is annotated with
@Component
it shouldn't be scanned in the first place but this code works perfectly. In fact for my use case having the bean in this class was the only way my problem was solved, but that is a different thing. Can anyone please explain this. Thanks !!

Answer

@SpringBootApplication is a meta annotation which looks like:

// Some details omitted
@SpringBootConfiguration
@EnableAutoConfiguration
public @interface SpringBootApplication { ... }

@SpringBootConfiguration is also a meta annotation:

// Other annotations
@Configuration
public @interface SpringBootConfiguration { ... }

And @Configuration is:

// Other annotations
@Component
public @interface Configuration { ... }

It works Since:

By default, classes annotated with @Component, @Repository, @Service, @Controller, or a custom annotation that itself is annotated with @Component are the only detected candidate components.