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