码迷,mamicode.com
首页 > 其他好文 > 详细

@component @bean区别

时间:2017-12-17 11:10:24      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:spring   exp   tomat   should   getter   this   ppi   post   flow   

from:

http://stackoverflow.com/questions/10604298/spring-component-versus-bean

http://stackoverflow.com/questions/27091553/are-bean-and-component-annotations-the-same-but-for-different-targets-in-sprin

 

@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.

看了一些文章,这两个注解可以互换使用,但还有一些使用目的进行区别的。

@Component被用在要被自动扫描和装配的类上。

@Bean主要被用在方法上,来显式声明要用生成的类。

现在项目上,本工程中的类,一般都使用@Component来生成bean。在把通过web service取得的类,生成Bean时,使用@Bean和getter方法来生成bean。

@component @bean区别

标签:spring   exp   tomat   should   getter   this   ppi   post   flow   

原文地址:http://www.cnblogs.com/shamo89/p/8051350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!