Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Architecture Questions: is Service needed?

I'm new to Spring and I'm creating a REST-Service. I wonder what the Service-Layer is for (@Service). Currently I encapsulate my DAOs with that Layer. So for example my PersonController receives a PUT, calls the PersonService which calls the DAO which finally saves the person in my database.

I also saw some examples in the www. (https://howtodoinjava.com/spring/spring-core/how-to-use-spring-component-repository-service-and-controller-annotations/)

I also have read this question here: Is this a good Spring Architecture (include testing)

Do I even need the Services, if it only calls the DAO like:

public void save(Person p) {
    personDAO.save(p);
}

?

I don't really see what the advantage of this is. I create classes which actually do nothing... Or is it just a architecture standard because additional business logic will be in this layer too?


Also... when I have several services like personService, familyService, animalService, etc. and they all have some method signatures that are the same and some which aren't... is it useful to use Interfaces here?

When I create Interfaces like: Saveable, Loadable, Deleteable (does this even make sense?) - how do I use them correctly? Do I create a new Interface for every service that extends the Interfaces I desire? Like a PersonServiceInterface that extends Loadable and Deleteable and I implement it in my PersonService?

Thanks in advance!

like image 784
KnechtRootrecht Avatar asked Oct 27 '25 06:10

KnechtRootrecht


1 Answers

If you do not feel the need for a service layer, then chances are high your controllers are performing way more business logic than they should.

adding a service layer in between allows for dedicated tests of pure frontend (controller handle request and response wiring only / services handle the business logic/ repositories persist and query the data).

so rule of thumb - it is much easier to have many services handle fractions of your logic than to stuff everything into your controllers

i am not sure what you are trying to solve with the interfaces you introduce - i do not think it makes sense to re-invent the Repository interface on top of your services. If your services only forward to repositories directly then there is no use in having them anyway.

like image 109
light_303 Avatar answered Oct 28 '25 21:10

light_303