1. 程式人生 > >@component @bean區別

@component @bean區別

使用 can rep choose scanning beans target ppr map

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區別