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.
3 Answers
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 :)
3 Comments
To put it in plain terms, @ComponentScan scans all the class files specified under the base package i.e. search for the files under this package for any annoted java files with @Component, @Repository, @Service and @Controller and if it finds any of them it will register it into the bean factory.
It was a pain to write everything in an XML file, where you have to specify what each class was, if it was a Service or a Controller, so Annotation came into the picture to avoid this...Internally it does the same thing like as if you had written a xml file which mentioned what was what
2 Comments
@Component is a generic annotation for any Spring-managed class/component.
@Component
class YourBusinessClass {
Dependency1 dependency1;
Dependency2 dependency2;
............
}
Whereas @Component-Scan annotation is used to scan the packages for any annotated java class/file (@Component, @Service, @Repository, etc).
@Component-scan also takes package name as an argument. If we don't specify it, by default it scans the current package.
@ComponentScan("com.user.package.config1")
public class BusinessApplication {
...............
}