最近翻了一下Spring In Action,看完前三章發(fā)現(xiàn)@Bean和@Component用得挺多,不過對這兩者的區(qū)別不是很清楚,書中也沒有詳細(xì)介紹。
Google了一下,發(fā)現(xiàn)一篇文章寫得不錯,不過是純英文的:http://www.tomaszezula.com/2014/02/09/spring-series-part-5-component-vs-bean/
下面是看過上面文章之后自己的一些理解:
首先我們看看這兩個注解的作用:
@Component注解表明一個類會作為組件類,并告知Spring要為這個類創(chuàng)建bean。
@Bean注解告訴Spring這個方法將會返回一個對象,這個對象要注冊為Spring應(yīng)用上下文中的bean。通常方法體中包含了最終產(chǎn)生bean實(shí)例的邏輯。
兩者的目的是一樣的,都是注冊bean到Spring容器中。
@Component(@Controller、@Service、@Repository)通常是通過類路徑掃描來自動偵測以及自動裝配到Spring容器中。
而@Bean注解通常是我們在標(biāo)有該注解的方法中定義產(chǎn)生這個bean的邏輯。
舉個栗子:
@Controller//在這里用Component,Controller,Service,Repository都可以起到相同的作用。@RequestMapping(″/web/controller1″)public class WebController { .....}
而@Bean的用途則更加靈活
當(dāng)我們引用第三方庫中的類需要裝配到Spring容器時(shí),則只能通過@Bean來實(shí)現(xiàn)
舉個例子:
public class WireThirdLibClass {@Beanpublic ThirdLibClass getThirdLibClass() {return new ThirdLibClass(); }}
再舉個只能用@Bean的例子:
@Beanpublic OneService getService(status) {case (status) { when 1:return new serviceImpl1(); when 2:return new serviceImpl2(); when 3:return new serviceImpl3(); }}
以上這個例子是無法用Component以及其具體實(shí)現(xiàn)注解(Controller、Service、Repository)來實(shí)現(xiàn)的。
總結(jié):@Component和@Bean都是用來注冊Bean并裝配到Spring容器中,但是Bean比Component的自定義性更強(qiáng)??梢詫?shí)現(xiàn)一些Component實(shí)現(xiàn)不了的自定義加載類。