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首选元件扫描和自动布线.
@Component Preferable for component scanning and automatic wiring.
什么时候应该使用 @Bean?
有时自动配置不是一种选择.什么时候? 假设你想从 3rd-party 库中连接组件(你没有源代码,所以你不能用 @Component 注释它的类),所以自动配置是不可能的.
Sometimes automatic configuration is not an option. When? Let's imagine that you want to wire components from 3rd-party libraries (you don't have the source code so you can't annotate its classes with @Component), so automatic configuration is not possible.
@Bean 注释返回一个对象,spring 应该在应用程序上下文中将其注册为 bean.方法体承载着负责创建实例的逻辑.
The @Bean annotation returns an object that spring should register as bean in application context. The body of the method bears the logic responsible for creating the instance.
这篇关于Spring:@Component 与 @Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!