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

后端 未结 29 2161
时光说笑
时光说笑 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:45

    all these annotations are type of stereo type type of annotation,the difference between these three annotations are

    • If we add the @Component then it tells the role of class is a component class it means it is a class consisting some logic,but it does not tell whether a class containing a specifically business or persistence or controller logic so we don't use directly this @Component annotation
    • If we add @Service annotation then it tells that a role of class consisting business logic
    • If we add @Repository on top of class then it tells that a class consisting persistence logic
    • Here @Component is a base annotation for @Service,@Repository and @Controller annotations

    for example

    package com.spring.anno;
    @Service
    public class TestBean
    {
        public void m1()
        {
           //business code
        }
    }
    
    package com.spring.anno;
    @Repository
    public class TestBean
    {
        public void update()
        {
           //persistence code
        }
    }
    
    • whenever we adds the @Service or @Repositroy or @Controller annotation by default @Component annotation is going to existence on top of the class

提交回复
热议问题