Where to write which code in Springboot Application

Rahi Shah
2 min readOct 19, 2021

--

Hello everyone, I was working on one of my projects for the last 2–3 months, and on one random day, I was scrolling my IntelliJ(The only friend who gives me the best advice when I am stuck in a problem) and I noticed that my controllers are having 300 lines of code and there are only 5 APIs !!

I researched about it and took guidance from my peers which made me realize the problematic point in code. Hence, I spent an entire week refactoring and I feel no one else should get into the same trouble and decided to write this blog

In Springboot App, we have below logical layers of code and the below description, tells where to write which code.

Controller

This layer contains almost no business logic and it only consumes requests from the outside world and converts the DTOs to Service-specific Object, calls the service, and after getting a response from the service layer it converts back to Response DTO and returns it to the outside world.

As this layer is not a transactional layer, the Controller can call multiple services only if they are not updating the state of DB. If there are different services that only get data from DB then the controller can do multiple service calls.

Service

Every business logic will come under this section. and generally, this layer is transactional(@Transactional) so if something breaks after executing the particular line we can do a rollback.

So you may ask like why do we have a controller if we are going to write every logic here?

Because If we want to support multiple consumers of which one is REST client & the other is a Non-REST client. Then both will implement their logic related to REST/Non-REST at the controller layer and then call this service which is reusable.

Repository

Here we should write the code related to DAO. Every code which will talk to DB should be written here. Generally in Springboot App, we use JPA, Every JPA repositories with @Repository or custom interface in which we write Query Dsl or Queries itself comes under the Repository abstraction layer.

Conclusion

  • Controller will consume the request from outside
  • Controller will convert request DTO to Service Expected Objects
  • Controller Calls Service
  • Service will call other Services & Repositories
  • Repository will do operations on DB and returns data to Service
  • Service will return the processed response to Controller
  • Controller will return the response to outside

--

--