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博客

相关推荐
刘火锅2 小时前
Bug 记录:SecureRandom.getInstanceStrong()导致验证码获取阻塞
spring boot·spring·spring cloud·bug
hrrrrb2 小时前
【Spring Boot 快速入门】八、登录认证(一)基础登录与认证校验
spring boot·后端
运维帮手大橙子2 小时前
完整的登陆学生管理系统(配置数据库)
java·前端·数据库·eclipse·intellij-idea
王大锤·2 小时前
基于spring boot的个人博客系统
java·spring boot·后端
bobz9653 小时前
QT designer 常用技巧
后端
shi57833 小时前
C# 常用的线程同步方式
开发语言·后端·c#
sg_knight3 小时前
Spring Cloud Gateway全栈实践:动态路由能力与WebFlux深度整合
java·spring boot·网关·spring·spring cloud·微服务·gateway
没逻辑3 小时前
抗量子密码技术(PQC)演变
后端·量子计算
JosieBook3 小时前
【IDEA】IntelliJ IDEA 中文官方文档全面介绍与总结
java·ide·intellij-idea
三只蛋黄派3 小时前
Websocket
java