Service Layer

Traditionally the service layer, or the "business layer" as it is also called, is where we code all the business logic for our application. This layer does not deal with matters like persistence or other infrastructural concerns. Each service should encapsulate a logical collection of transactions. Most service will use repositories (data access objects) because most services do the things that are related to the databases. However, not all service methods are required to use a repository.

Having the service layer be a wrapper around the DAO is a common anti-pattern. Using a service layer means that we get several benefits:

  • Helps in decoupling of responsibilities. It gives us a clear distinction between web type activity which is best done in controller and generic business logic that is not web-related. We can test service-related business logic separately from controller logic.
  • We can specify transaction behavior. If we need to call methods from multiple data access objects we can specify that they occur within the same transaction.

In following sections we will implement this layer.