免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
Spring中@Component與@Bean的區(qū)別

最近翻了一下Spring In Action,看完前三章發(fā)現(xiàn)@Bean和@Component用得挺多,不過對(duì)這兩者的區(qū)別不是很清楚,書中也沒有詳細(xì)介紹。

Google了一下,發(fā)現(xiàn)一篇文章寫得不錯(cuò),不過是純英文的:http://www.tomaszezula.com/2014/02/09/spring-series-part-5-component-vs-bean/

下面是看過上面文章之后自己的一些理解:

首先我們看看這兩個(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)通常是通過類路徑掃描來(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í),則只能通過@Bean來(lái)實(shí)現(xiàn)

舉個(gè)例子:

public class WireThirdLibClass {@Beanpublic ThirdLibClass getThirdLibClass() {return new ThirdLibClass();    }}

再舉個(gè)只能用@Bean的例子:

@Beanpublic 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)不了的自定義加載類。

? 著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Spring Annotation 詳解
Spring3 MVC詳解二
Spring常用注解
SpringBoot-常見問題(一)
springboot注解整理
spring @component的作用
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服