Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring service and repository layer convention

I start working with Spring and have some confusions about its conventions.

  1. Is it fine to put Repositories in Controller?
  2. In a Service class, If I want to reuse code could I inject other Services and other Reposities?
  3. is it the best practice to name Service And Repository class is based on Entity name i.e: User -> UserRepository->UserService?
like image 272
Mai Hữu Lợi Avatar asked Dec 03 '15 05:12

Mai Hữu Lợi


People also ask

Can we use @service instead of @repository?

According to documentaion @Repository , @Service , @Controller are all synonyms. They all are just specializations of @Component annotation. So, generally, they can be used one instead of other.

What is the difference between @service and @repository?

@Service annotation is used with classes that provide some business functionalities. @Repository Annotation is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects. @Service Annotation is a specialization of @Component Annotation.

What is the difference between @component @repository @service and @controller?

@Component is a generic stereotype for any Spring-managed component or bean. @Repository is a stereotype for the persistence layer. @Service is a stereotype for the service layer. @Controller is a stereotype for the presentation layer (spring-MVC).

What is difference between @component and @service?

@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.


1 Answers

  1. No, don't use Repositories in the Controller. Only in the Services. And don't use Entities in your Controller. Create Dto (Data Transfer Objects) Object from the Entities and work with this in your frontend

    1. Yes you can use other services and respositories in your service class

    2. Yes it is. Name the interfache UserService and the implementation UserServiceImpl

like image 198
Si mo Avatar answered Oct 15 '22 04:10

Si mo