Spring 中 @Component 和 @Bean 区别

Spring 中 @Component 和 @Bean 区别

文章目录

  • [`Spring` 中 `@Component` 和 `@Bean` 区别](#Spring 中 @Component 和 @Bean 区别)

1. 用途不同

​ @Component 用于标识一个普通的类 ,@Bean用于配置类 里面,在方法上面声明和配置 Bean 对象

Tips:

  1. @Component 会告诉 Spring,由 @Component 所修饰的类会被作为组件类,同时 Spring 要为这个类创建 Bean
  2. 告知spring这个方法会返回一个对象,这个对象需要注册为Spring上下文(ApplicationContext)中的bean,通常方法体包含了最终产生 bean 实例的逻辑

2.使用方式不同

​ @Component 是类级别 的注解,Spring 可以扫描到配置此注解的这些类并把他们注入到 SpringIOC 容器中,@Bean 是修饰在方法上 的,表示此方法返回一个 Bean 对象注入到 SpringIOC 容器中。

Tips:但是都能够在 Spring 中注册Bean对象

@Component 使用示例

Java 复制代码
@Component
public class OrderService {
}

但是在spring中通常@Component注解通常要配合@ComponentScan实现注册的功能

java 复制代码
@ComponentScan("指定@Component注解所在的包路径")
public class AppConfig {
    
}

@Bean 使用示例

java 复制代码
@Configuration
public class AppConfig {
 
    @Bean
    public OrderService orderService1(){
        return new OrderService();
    }
}

@Bean需要在配置类 中使用,即类上需要加上@Configuration注解,然后在配置类中使用一个方法定义bean是如何创建的

3. 控制权不同

​ @Component 修饰的类是由Spring框架 统一管理和创建的,而 @Bean 允许开发人员手动控制 Bean的创建和配置

4. 灵活性不同

@Bean注解比@Component注解灵活,我们可以按需注册需要的bean,很多场景我们只能通过@Bean来注册bean,比如引入第三方库中的类需要装配到spring容器中。

参考文献

  1. Spring中@Component注解和@Bean的区别是什么-CSDN博客

  2. Spring中@Component和@Bean的区别_spring bean和component-CSDN博客

相关推荐
马良神笔14 分钟前
2026 年Rag最近技术前沿总结
后端·python·django
程序猿DD14 分钟前
同样10美元,OpenDesign和Command Code的DeepSeek V4.1 Flash额度到底有多少?
后端
福兮说37 分钟前
JSON 格式正确,数据就可靠吗?我用一份自编配置检查类型与空值
java·前端·json
高频因子挖掘机43 分钟前
A股量化从日线升级到5分钟线:数据量增加后最先暴露哪些工程问题?
后端·github·api
高频因子挖掘机1 小时前
历史行情返回顺序变了,为什么按行号计算指标很危险?
后端·github·api
紧跟先前的步伐2 小时前
Go AI Agent 实战 03|Token、上下文窗口与模型调用成本
java·人工智能·golang
const_qiu2 小时前
第四章 00:开篇 —— 从「会聊天」到「记得住、会干活、能协作」
java·开发语言·人工智能·python
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 个人资料管理的更新接口实现与坑
java·开发语言·交友
团子哒哒3 小时前
数组、切片和Map
后端
Promising_GEO3 小时前
GEE实战02期:从卫星波段开始:利用 Sentinel-2 自己计算 NDVI
java·sentinel·遥感·空间分析