@Component @Controller @Service @Repository区别

很多地方只讲了@Component @Controller @Service @Repository四者的用法,并没有讲区别。

本文讲下四者区别,帮助大家加深这四者的理解。

四者分别的作用

四者相同点

  1. 声明当前类是Spring Bean,可以被Spring容器所管理
  2. 可以配合Spring的自动扫描在Spring容器中注册成Bean
  3. 在Spring中注册Bean这一层面,四者可以互相替换通用

四者的区别

  1. <context:component-scan>只会扫描@Component注解,不会扫描@Controller, @Service和@Repository
  2. @Controller、@Service和@Repository之所以最后被识别是因为他们三者在定义的时候都被声明为@Component
    @Component
    public @interface Service {
        ….
    }
    

     

    @Component
    public @interface Repository {
        ….
    }
    

     

    @Component
    public @interface Controller {
        …
    }
    所以@Controller、@Service、@Repository是@Component的具体细分
  3. @Repository注解可以额外捕获平台特定异常,可以帮助抛出数据访问异常
  4. @RequstMapping需要用在被标注了@Controller注解上,不适用于@Component、@Service、@Repository
  5. @Service这个注解目前没有特别之处,或许将来会被赋予额外的功能
  6. 对于@Repository,@Controller和@Service,我们还是建议根据它们的属性在特定层面上正确标注,因为保不齐后面会根据所属层面赋予特定的功能

以上供参考。

posted @ 2022-03-15 18:21  淡谷子  阅读(238)  评论(0)    收藏  举报