Ekaterina
Ekaterina

Reputation: 1892

What's the use of @ComponentScan annotation if all the beans can be annotated with @Component?

Why do we need to write @Component annotations and then again write @ComponentScan in Spring? We can define @ComponentScan with a special package , but I'can imagine a scenario when we annotate a class as a @Component and then exclude it from search.

Upvotes: 0

Views: 230

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40048

In simple words @Component is used to mark a class as bean that are need to identified during @componentscan,

And @componentScan only look for the beans that are annotated with @Component and create beans for them.

Usually @ComponentScan will scan all classes and sub packages classes, but if you have any classes in other packages that are not sub packages of main package, then you should manually add them in @ComponentScan

If you look at documentation all @Controller , @Service are annotated with @Component

@Component
public @interface Controller {
…
}
@Component
public @interface Controller {
…
}

Upvotes: 2

Related Questions