SpringBoot:@Component, @Service, @Repository, @Controller, @Bean使用说明

@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扫描将自动侦测到.
2Spring容器甚至是Spring容器外的类也能被创建为beanSpring容器外的类不能被创建
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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值