春季:@Component与@Bean [英] Spring: @Component versus @Bean

查看:267
本文介绍了春季:@Component与@Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知, @Component 标注是在春季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 春季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)之间的隐含一个一对一的映射。布线的控制是十分赞同这种做法限制,因为它是纯声明。

@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,而不是让春自动做如上。它能够消除类定义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.

要回答你的问题...

To answer your question...

将它一直可能重新使用 @Component 注释,而不是引入 @Bean 标注?

would it have been possible to re-use the @Component annotation instead of introducing @Bean annotation?

当然,可能;但他们没有选择,因为两者有很大的不同。 Spring的已经够混乱的,无需进一步污浊的水。

Sure, probably; but they chose not to, since the two are quite different. Spring's already confusing enough without muddying the waters further.

这篇关于春季:@Component与@Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆