by BehindJava

When to use service or component in spring

Home » springboot » When to use service or component in spring

In this tutorial we are going to learn about using service or component in spring.

In order to “configure” Spring so it can provide you with the instances of the classes you need, you are supposed to tell Spring what objects are involved and how they are built. To do this you can use an xml configuration file or through annotations

In case you take the annotation approach (IMHO a much better and simpler one) you can use @Component to annotate the class. This is like telling Spring: “Hey! I want you to know that you may need an instance of this class. Maybe because I request it, maybe because something I requested needs it”. So annotating a class with @Component just let Spring know that it exists

There are other annotations that do the same:

  • @Controller (and @RestController)
  • @Service
  • @Repository

They all inform Spring that the class is involved in the DI context. But they also have semantic meaning:

  • @Controller = @Component belonging to Presentation Layer
  • @Service = @Component belonging to Service/Use Case Layer
  • @Repository = @Component belonging to Persistence Layer

You can find more info in this question

Should a service be able to call the other services?

I don’t see any problem with that. If any of your services requires to do some actions that are already performed by other you surely want to avoid code duplication. As long as you respect the architecture layers dependency (never going up) you’ll be fine.