Bonifacy M
Bonifacy M

Reputation: 105

Spring MVC best practices

I am developing a Spring MVC web application and I keeps JPA entities in repository package, dao's and controller classes in separate packages with jsp's in a folder in WEB-INF.

My question is, in this app, what is the model, what is the controller and what is the view? Where should I keep the business logic (dao or controller)? What is the best practice in terms of clear separation of business logic?

Upvotes: 4

Views: 2110

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149195

For what you are describing, the layers are as follow :

  • view : JSP files
  • controller : the DispatcherServlet (front controller) and you controller classes
  • model : all what remains

For the latter part of your question, you are in fact asking for opinion based answers. But the following seems to be a common pattern :

If you put business logic in controller you get a Fat Stupid Ugly Controller (just google around). Even if Spring MVC gives you tools to test controllers, the common usage is to avoid it, because the controller is heavily dependent on framework, and it is best to make business logic as independent as possible of framework. One never knows, you may have to use a different framework later for any reason.

It is equally bad to put business logic in DAO for same reason : framework independance.

My advice is to add a service layer between controller and DAO, with a possibility of exception for a true CRUD application. It is a layer with less framework dependance ; and in fact the reason why it is generally not produced by framework : the framework cannot know your business logic. There's another reason for the service class, it is the layer where transaction demarcation should live : controllers hardly support JDK proxying (which is the default transaction demarcation in Spring framework), and it can be relevant to call more than one DAO method in one single transaction.

But I must admit that the above is my opinion and not the big truth (well not only mine, but definitely an opinon). You can certainly find use cases where business logic is so tiny that it does not require the overhead or a service layer : it is just an architectural choice, and provided you know why you make the choice any possibility can be good.

Upvotes: 5

Related Questions