@Component, @Service, @Repository, @Controller,它们都是spring提供的模式化注解(stereotype annotation),位于org.springframework.stereotype包下,它们之间的继承关系如下:
Spring在启动过程中会自动加载标记了这些注解的类,并将它们的实例注册到ApplicationContext中。
它们的主要区别在于它们使用在不同的分类中:
注解 | 描述 |
@Component | 是一种通用的模式,可以用在由Spring管理的所有组件上 |
@Service | 主要用在业务逻辑层组件上 |
@Repository | 主要用在数据访问层组件上,当捕获到持久化层特定的异常后,会包装成Spring统一的unckeck异常,并向外抛出 |
@Controller | 主要用在展示层组件上 |
@Bean位于org.springframework.context.annotation下,以下是@Bean与@Component的比较:
Key | @Bean | @Component | |
---|---|---|---|
1 | 自动侦测 | 需要明确声明为单例bean,Spring不会自动初始化 | 只要类声明了注解@Component, classpath扫描将自动侦测到. |
2 | Spring容器 | 甚至是Spring容器外的类也能被创建为bean | Spring容器外的类不能被创建 |
3 | 类级/方法级注解 | 方法级注解 | 类级注解 |
4 | @Configuration | 只能与带@Configuration注解的类一起使用 | 不需要与@Configuration一起使用 |
5 | 用例 | 如果想要基于动态条件的特定实现,应该使用@Bean | 无法实现基于动态条件的特定实现 |
参考文档
Spring @Component, @Service, @Repository, @Controller Difference
https://javapapers.com/spring/spring-component-service-repository-controller-difference/
@Component vs @Repository and @Service in Spring
https://www.baeldung.com/spring-component-repository-service
Spring Bean Annotations
https://www.baeldung.com/spring-bean-annotations
Difference between @Bean and @Component annotation in Spring
https://www.tutorialspoint.com/difference-between-bean-and-component-annotation-in-spring