0

Suppose I have a Spring application divided into 3 layers: controller, service and repository. In which layer should all the business logic go? From what I have read on the net, the controller should only consume the service and it is the service that should be the one that contains all the business logic. Is this correct? Should I handle the Exception that may occur in the service?, I'm quite new to Spring and not sure which is the correct way to approach and which are the best practices.

Jan B.
  • 6,030
  • 5
  • 32
  • 53
Ricki
  • 141
  • 3
  • 16

2 Answers2

2

Into services.

  1. Repo - interaction with database
  2. Controller - Http communication handling (or other type if interaction like CLI)
  3. Service - bussiness logic.
Antoniossss
  • 31,590
  • 6
  • 57
  • 99
  • and exceptions where should y be handling them? in the service? – Ricki May 31 '18 at 20:25
  • 1
    Depends on scenario but I would say yes, in most cases – Antoniossss May 31 '18 at 20:26
  • It's also quite common that the exception is handled in the Controller. For instance, a Service throws a _UserNotFoundException_ and the Controller catches it and responds with a 404 to the requesting client following the restful principle. – Jan B. May 31 '18 at 20:32
  • @Matt this whas my aproach but not sure if it was correct – Ricki May 31 '18 at 20:38
  • 2
    @Ricki as Antoniossss said, it really depends. There are examples for exceptions to be thrown, caught and handled in each of the three layers. I guess there is no rule, and thus, it can be tricky some time. Reading some Spring tutorials on Exception Handling is probably a good start. – Jan B. May 31 '18 at 20:42
1

You should put all your business logic into the Service Layer.

Commonly, exceptions are, also, handled at the Service Layer. This happens mainly because of the reusability. However, in Spring Applications, generally, even the service layer throw the exceptions, so that you can centralize all the errors in a single handler class.

Read more at Spring MVC Exception Handling.

Matheus
  • 3,058
  • 7
  • 16
  • 37