I'm bit confused about these annotations, since I am very new to Spring. I tried to get it on google and found many answers but still, I did not got the clarity. I got to know that @Component is Super annotation for @Repository, @Service and @Controller, but I'm still in doubt when to use @Component and when to Use @ComponentScan Could any one help me to get clear understanding of these both annotations, and what is difference in both.
Using the annotation @ComponentScan , you can tell Spring where do your Spring-managed components lie. These Spring-Managed components could be annotated with @Repository,@Service, @Controller and ofcourse @Component.
For example - Lets say your spring-managed components lie inside 2 packages com.example.test1 and com.example.test2. Then your componentScan would be something like this
@ComponentScan(basePackages="com.example.test1","com.example.test2")
OfCourse the annotation ComponentScan has a lot of other elements.
You can read more about them here - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/ComponentScan.html.
On the other hand, @Component is a generic annotation for any Spring-Managed component. For example - If you create a class called Testing inside the package com.example.test1 and annotate with Spring @Component.
@Component
Class Testing
{
public Testing()
{
}
public void doSomething()
{
System.out.println("do something");
}
}
Following the above example, During Component Scan it will be picked up and added to the application context.
Hope this makes things clear :)