Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 3-2.Fine-Grained Service Layer Interface

public interface FineGrainedAccountManager {
Account findAccountByUsername(String username);

void setAccountToActive(Account account);

boolean accountAbleToBeActivated(Account account);

void sendActivationEmail(Account account, Mailer mailer);
}

With the preceding example, too much responsibility is given to the client. What is the
correct order of the method calls? What happens if there is a failure? There’s no way to guaran-
tee that the same account instance is used for every call. This fine-grained interface couples
the client too closely to howthe use case is implemented.
In environments where the client is remote, a coarse-grained interface is an important
design element. Serialization is not a cheap operation, so it is important to serialize at most
once per call into the service layer. Even in systems where the client is in the same virtual
machine, this layer plays a crucial role when separating the concerns of the system and mak-
ing it easier to decouple and test.

Dependencies
The service layer is dependent upon the domain model and the persistence layer, which we
discuss in the following sections. It combines and coordinates calls to both the data access
objects and the domain model objects. The service layer should never have a dependency on
the view or web layers.
It is important to note that it is usually unnecessary for this layer to have any dependen-
cies on framework-specific code, or infrastructure code such as transaction management. The
Spring Framework does a good job of transparently introducing system aspects so that your
code remains highly decoupled.

Spring’s Support for the Service Layer
The Spring Framework does provide any interfaces or classes for implementing the business
aspects of the service layer. This should not be surprising, because the service layer is specific
to the application.
Instead of defining your business interfaces, Spring will help with the programming model.
Typically, the Spring Framework’s ApplicationContextwill inject instances of the service into
the web Controllers. Spring will also enhance your service layer with services such as transac-
tion management, performance monitoring, and even pooling if you decide you need it.

Summary
The service layer provides a stateless, coarse-grained interface for clients to use for system
interaction. Each method in the service layer typically represents one use case. Each method
is also one transactional unit of work.

30 CHAPTER 3 ■SPRING MVC APPLICATION ARCHITECTURE

Free download pdf