What's the difference between @Component, @Repository & @Service annotations in Spring?

后端 未结 29 2177
时光说笑
时光说笑 2020-11-22 00:33

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?

29条回答
  •  不知归路
    2020-11-22 00:51

    In order to simplify this illustration, let us consider technicality by use case, These annotations are used to be injected and as I said literally "Used to be injected" , that mean, if you know how to use Dependency Injection "DI" and you should, then you will always look for these annotations, and by annotating the classes with these Stereo Types, you are informing the DI container to scan them to be ready for Injection on other places, this is the practical target.

    Now lets move to each one; first @Service, If you are building some logic for specific business case you need to separate that in a place which will contain your business logic, this service is normal Class or you can use it as interface if you want , and it is written like this

    @Service
    public class Doer {
       // Your logic 
    }
    
    // To use it in another class, suppose in Controller 
    @Controller
    public class XController {
     // You have to inject it like this 
     @Autowired 
     private Doer doer;
    }
    

    All are the same way when you inject them, @Repository it's an interface which apply the implementation for the Repository Pattern Repository design pattern, generally it's used when you are dealing with some data store or database, and you will find that, it contains multiple ready implementation for you to handle database operations; it can be CrudRepository, JpaRepository etc.

    // For example
    public interface DoerRepository implements JpaRepository {}
    

    Finally the @Component, this is the generic form for registered beans in Spring, that's spring is always looking for bean marked with @Component to be registered, then both @Service and @Repository are special cases of @Component, however the common use case for component is when you're making something purely technical not for covering direct business case! like formatting dates or handing special request serialization mechanism and so on.

提交回复
热议问题