欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

一文掌握Spring 中 @Component 和 @Bean 区别(最新推荐),

来源: javaer 分享于  点击 34482 次 点评:45

一文掌握Spring 中 @Component 和 @Bean 区别(最新推荐),


目录
  • 1. 用途不同
  • 2.使用方式不同
  • 3. 控制权不同
  • 4. 灵活性不同

Spring@Component@Bean 区别

1. 用途不同

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

Tips

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

2.使用方式不同

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

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

@Component 使用示例

@Component
public class OrderService {
}

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

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

@Bean 使用示例

@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容器中。

参考文献

Spring中@Component注解和@Bean的区别是什么

Spring中@Component和@Bean的区别_spring bean和component

到此这篇关于Spring 中 @Component 和 @Bean 区别的文章就介绍到这了,更多相关Spring @Component 和 @Bean 区别内容请搜索3672js教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持3672js教程!

您可能感兴趣的文章:
  • SpringBoot在容器中创建实例@Component和@bean有什么区别
  • Spring @bean和@component注解区别
  • Spring注解开发@Bean和@ComponentScan使用案例
  • spring-boot @Component和@Bean的区别详解
相关栏目:

用户点评