Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a spring service annotation? [duplicate]

Tags:

I understand that @Service is used to mark a class as a business logic class. Why is it useful for spring? I can already use @Component to mark a class as a bean. I understand that @Service is more specific than @Component, but how?

like image 913
webpersistence Avatar asked Dec 06 '17 07:12

webpersistence


2 Answers

Consider @Component annotation as a Swiss Knife. It can act as cutting knife, as an opener, as a scissor, etc.

Component

Similarly, your Component can act as a Repository, as Business Logic class or as a controller.

Now, @Service is a just one of the versions of @Component, say a knife.

Spring process @Service similar to @Component, since @Service interface itself is annotated with @Component.

From Spring docs.:

@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Component public @interface Service 

Indicates that an annotated class is a "Service" (e.g. a business service facade).

Why to differentiate both of them?

To apply the basic rule of programming: Your code should be easily readable.

Yes, you can use @Component annotation everywhere and it will work fine but for the better understanding of the code, it is preferred to use the respective special types of annotations like @Service in our case.

The other benefit is ease of debugging. Once you know the error, you need not hope from one component class to another, checking it time whether that class is service, repository or controller.

like image 175
Dhaval Simaria Avatar answered Sep 20 '22 11:09

Dhaval Simaria


@Service, @Controller, @Repository = {@Component + some more special functionality}

Click the below link for more details

What's the difference between @Component, @Repository & @Service annotations in Spring?

The @Component annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. The @Service annotation is also a specialization of the component annotation. It doesn’t currently provide any additional behavior over the @Component annotation, but it’s a good idea to use @Service over @Component in service-layer classes because it specifies intent better. Additionally, tool support and additional behavior might rely on it in the future.

like image 44
Sankar Avatar answered Sep 20 '22 11:09

Sankar