@Component @Controller @Service @Repository区别
很多地方只讲了@Component @Controller @Service @Repository四者的用法,并没有讲区别。
本文讲下四者区别,帮助大家加深这四者的理解。
四者分别的作用
四者相同点
- 声明当前类是Spring Bean,可以被Spring容器所管理
- 可以配合Spring的自动扫描在Spring容器中注册成Bean
- 在Spring中注册Bean这一层面,四者可以互相替换通用
四者的区别
- <context:component-scan>只会扫描@Component注解,不会扫描@Controller, @Service和@Repository
- @Controller、@Service和@Repository之所以最后被识别是因为他们三者在定义的时候都被声明为@Component
@Component public @interface Service { …. }@Component public @interface Repository { …. }
所以@Controller、@Service、@Repository是@Component的具体细分@Component public @interface Controller { … } - @Repository注解可以额外捕获平台特定异常,可以帮助抛出数据访问异常
- @RequstMapping需要用在被标注了@Controller注解上,不适用于@Component、@Service、@Repository
- @Service这个注解目前没有特别之处,或许将来会被赋予额外的功能
- 对于@Repository,@Controller和@Service,我们还是建议根据它们的属性在特定层面上正确标注,因为保不齐后面会根据所属层面赋予特定的功能
以上供参考。

浙公网安备 33010602011771号