When to use service or component in spring?

ChiaChih wu picture ChiaChih wu · Sep 18, 2017 · Viewed 18.2k times · Source

When to use service or component in spring?

For example, is a module responsible for sending email or common business logic a "service" or a "component"? and what's the difference?

Is a service able to call the other services? Is there any transaction problem? or a service should call the components only?

Someone told me that a service should never call the other services and should only call the components instead, which means Controller->Service->Component->DAO, but I found many people share the concept of Controller->Service->DAO with no component.

Is there any system design criteria about this topic in Spring?

Answer

Pelocho picture Pelocho · Sep 18, 2017

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.

About this you can check this article about Clean Architecture