Spring:@Component 与 @Bean [英] Spring: @Component versus @Bean
问题描述
我知道 @Component
注释是在 spring 2.5 中引入的,目的是通过使用类路径扫描来摆脱 xml bean 定义.
I understand that @Component
annotation was introduced in spring 2.5 in order to get rid of xml bean definition by using classpath scanning.
@Bean
是在 spring 3.0 中引入的,可以与 @Configuration
一起使用,以完全摆脱 xml 文件并使用 java 配置代替.
@Bean
was introduced in spring 3.0 and can be used with @Configuration
in order to fully get rid of xml file and use java config instead.
是否可以重用 @Component
注释而不是引入 @Bean
注释?我的理解是,最终目标是在两种情况下都创建 bean.
Would it have been possible to re-use the @Component
annotation instead of introducing @Bean
annotation? My understanding is that the final goal is to create beans in both cases.
推荐答案
@Component
和 @Bean
做两件完全不同的事情,不应混淆.
@Component
and @Bean
do two quite different things, and shouldn't be confused.
@Component
(以及@Service
和@Repository
)用于使用类路径扫描自动检测和自动配置bean.在带注释的类和 bean 之间存在隐式的一对一映射(即每个类一个 bean).这种方法对接线的控制非常有限,因为它纯粹是声明性的.
@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
用于显式声明单个 bean,而不是让 Spring 像上面那样自动执行.它将 bean 的声明与类定义分离,让您可以完全按照自己的选择创建和配置 bean.
@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.
要回答您的问题...
是否可以重用 @Component
注释而不是引入 @Bean
注释?
would it have been possible to re-use the
@Component
annotation instead of introducing@Bean
annotation?
当然,可能;但他们选择不这样做,因为两者完全不同.春天已经够混乱了,但没有进一步搅浑水.
Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.
这篇关于Spring:@Component 与 @Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!