I use Spring Boot and Spring Data.
I have no problem in my mind to separate Repository Layer and Service Layer
So I have my UserRepository with CRUD method and some Spring Data method
I also have UserService with business method.
Here is my question:
In my controller I have to call method from UserService and sometime from UserRepository. For the moment, I inject both in my controller, and I call service or repository
@Inject
UserService userService;
@Inject
UserRepository userRepository;
@RequestMapping("{username}")
private void myMethod(@PathVariable String username){
return userRepository.findOne(username);
}
@RequestMapping("{username}/doBusineesAction")
private void myMethod(@PathVariable String username){
return userService.doLogicalThin(username);
}
I'm just asking because I confused to inject both and to call one or the other in the same class
On another side, this would mean to duplicate method in service layer like this
public User findOne(String username){
return userRepository.findOne(username);
}
What's your opinion?
Yes, it is a bad practice. Controller should be used only to control the flow of your application, get input from client apps, call service and pass data to the view (JSON/HTML/XML/etc). Repository/DAO should be used to retrieve/persist the data without knowing any business logic.
There are no problem occur when I interchange the @service and @repository annotation in the spring MVC.
Here's a quick overview of a few of these annotations: @Component is a generic stereotype for any Spring-managed component. @Service annotates classes at the service layer. @Repository annotates classes at the persistence layer, which will act as a database repository.
@Repository Annotation is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. @Controller annotation indicates that a particular class serves the role of a controller. @Service Annotation is a specialization of @Component Annotation.
Controller layer shouldn't ever call repository directly. You should always use the service layer because the service layer encapsulates your business logic surrounding that call. Just because currently there isn't any business logic, doesn't mean that you should skip the layer entirely.
If your controller does not require business logic or perform a single repository operation, you can use the repositories directly. Use services to implement use cases that require business logic or orchestration of repository calls.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With