@Bean, @Component, @Configuration简析

本文详细解释了Spring框架中@Bean和@Component注解的区别。@Bean用于明确声明一个单例bean,允许自定义初始化和配置。而@Component则是用于类的自动扫描和bean的声明,适用于简单的一对一映射。@Configuration则用于定义配置类,包含多个@Bean方法,提供更灵活的依赖注入控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Bean

作用于方法,声明该方法产生的对象为bean,由spring Ioc统一初始化、装配、管理。该方法一般置于@configuration作用的类中。

@Configuration

作用于类,该类通常包含若干由@Bean修饰的方法。@Configuration表明该类由Spring Ioc统一管理、定义类,并提供服务请求、配置依赖关系。

@Component

作用于类,使该类中的bean能够在classpath 扫描中被探测到,@Configuration的功能大于@Component, @Component的功能大于@Bean

摘抄自stackoverflow的一段话:很有道理,不翻译了

@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

参考链接

explanation in stackoverflow

@Component vs @Bean

Component annotation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值