When we define the annotations “ @Component, @Service, @Controller, @Repository” with the classes, Spring automatically scan and identifies those classes and register the Bean definition with the ApplicationContext.
Difference between @Component, @Repository, @Controller & @Service annotations in Spring:
- The main difference between @Component, @Repository, @Controller & @Service annotations is that these are used for different classification.
- In our application we can have different layers like presentation, service, business, data access etc. To annotate a class for auto-detection by Spring, we should use the respective annotations as below.
@Component – generic and can be used across the application. It is a basic auto component scan annotation, it indicates annotated class is a auto scan component.
@Service – annotate classes at service layer level ( Indicates a Service component in the business layer).
@Controller – annotated class indicates that it is a controller components, and mainly used at presentation layer.
@Repository – a data access object (Indicates DAO component in the persistence layer which will act as database repository).
- We can use @Component for any auto component scan, but for better readability and better standards we should use respective annotations. @Repository, @Controller & @Service annotations serve as specializations of @Component annotation.
For Example of @Service and @Repository, Visit full Blog: What’s the difference between @Component, @Repository, @Controller & @Service annotations in Spring?
You can check more informative blogs and tutorials at java development blogs section and can also browse the java questions and answers forum for posting and viewing latest questions on Java development.
Apart from this, If you have any Php issue, you can post it at Php Questions and answers forum.