Reputation: 11
( But as per as i know, it is mediator b/w controller and DAO layers. ) or Can we take dao dependencies in controller directly , is it good practice !! ??? as i shown below
@Controller
public class HomeController {
// @Autowired
// private UserServiceImpl userService;
@Autowired
private UserDAOImpl userDAOService;
@RequestMapping(value = "login", method = RequestMethod.GET)
public String login(..){
// String res = userService.someOperation();
String res = userDAOService.someOperation();
............
}
}
Upvotes: 1
Views: 6294
Reputation: 107
One good reason why we need Service layer is for loose coupling:
Lets say you have 100 api's in your controller class and 20 dao methods serving them.
Now if you directly call dao methods in the controllers, and at later point of time you want to have different dao methods serving these controllers.
You have to change all your 100 controllers right?
So if have 20 service methods calling those 20 dao methods.
Now if you want to change your dao methods serving these 100 controllers, you can just change the service methods(i.e 20 methods) to point to new doa methods rather than changing your 100 controller classes.
That's how you achieve loose coupling and is a better way of programming. Hope this helps you :)
Upvotes: 6
Reputation: 138
Generally it is a bad pratice to mix, Controller and Dao or Controller and Service.
The main reason for using DAO is to seperate database functions from business operations/logic. Also using DAO and Services in project enables loose coupling i.e (less dependent on one another)
And as far as business logic is concerned here's an example of Cash withdrawal from ATM
This flow is your business logic.
Upvotes: 1
Reputation: 2320
Generally putting DAO's directly into the controller is a bad idea unless the Controller is very simple (as in one method of less than 10 lines - maybe a unit test). That doesn't necessarily mean that you absolutely must split the services into a separate deployable. For many smaller projects, the "services" are interfaces packaged directly with the rest of the application.
Where a service layer is going to help is when you have a larger application, especially if those services are performing different roles. For example, if your business is manufacturing and your inventory services receive lots of traffic, you might split that into a service in its own deployable, and put your user management and marketing into a separate deployable. The advantage of splitting services out like this is that you can scale the busy services independently. For example, if you're running on AWS, it makes more sense to scale the inventory service by itself rather than scaling the whole application just because one piece gets called all the time.
Upvotes: 2