Pages

Monday, 3 September 2012

Spring MVC-Service-DAO-Persistence Architecture Example

It is considered good practice to use modularity across Spring web applications. It keeps them maintainable and testable. This can be achieved by using controllers, services and data access objects (DAO). Typically, a user request is handled by a controller, which calls a service, which calls a data access object, which calls the persistence layer implementation.

Using services means that application functionalities can be tested without a test framework simulating user calls to controllers. Separating services from the persistence layer implementation via DAO, allows using an in-memory database (for example) by substituting production DAO implementations, by test DAO implementation pointing to an in-memory database.

MVC Controller Calls The Service Implementation

The following controller is injected with an implementation of MyService. It handles /roundtrip user calls by calling its create() and Retrieve(id) methods, which creates and retrieves an instance of a MilliTimeItem object. It contains a unique ID and a timestamp in milliseconds.

4 comments:

I think making your DAO's transactional (using @Transactional annotation on DAO) is bad practise. Your services should be transactional and not DAO's. Your DAO's should not have knowledge of transactionality. For unit testing DAO's individually, one can use a framework like Spring testing framework to automatically start a transaction before DAO call. This is usually done by marking the test class as Transactional