15 Juta per Bulan dari Bisnis Wifi Rumahan, Minim Modal!
Difference between @Component, @Controller, @Service, and @Repository Spring Annotations - Java
Spring 2.0 has @Repository annotation, which is used as marker annotation. Currently a bean marked by @Component is also a Spring bean and a bean marked by @Service is also a spring bean, but they can be differentiated in future to associated Service level responsibility like transaction to a bean which is annotated by @Service, while @Component is a general purpose annotation to mark a Java object as Spring managed bean.
An example of @Component, @Service and @Repository annotation in Spring
As I said, you can use any of these annotation to mark a Java class as Spring managed bean, but using them in right context is what you need. Annotating a Service class with @Service gives Spring flexibility to do some automation, which is needed by Service classes e.g. transaction management. Currently Spring provides
Here is a simple example to see, where to use @Component, @Controller, @Service and @Repository annotation is Spring based Java applications.
@Servicepublic class TradeServiceImpl implements TradeService{ @Autowired private TradeDAO tradeDAO; }@Repositorypublic class TradeDAOImple implements TradeDAO{ }@Componentpublic class Trade{ }
In short,
@Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean, when annotation based configurations are used.
@Controller is a specific type of component, used in MVC applications and mostly used with @RequestMapping annotation.
@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
@Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
That’s all about the difference between @Component, @Service, and @Repository Spring Annotations. The key thing is when to use which annotation. So for general purpose just use @Component annotation to mark a Java class as bean but if its part of Service layer then use @Service to allow Spring do some magic for you and if its part of persistence layer then use @Repository for similarly purpose.
Thanks for reading this article so far. If you like my explanation of difference between Component, Service, and Repository annotation in Spring framework and then please share them with your friends and
colleagues. If you have any questions or feedback, then please drop a
note.