国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

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

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

最近翻了一下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)不了的自定義加載類。

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

聯(lián)系客服