日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

【Spring学习】spring注解自动注入bean

發布時間:2024/4/14 javascript 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Spring学习】spring注解自动注入bean 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Spring mvc注解用到的配置:

<!-- 啟用spring mvc 注解 --> <context:annotation-config /> <context:component-scan base-package="cn.itkt"></context:component-scan>

這樣的話,在com包及其所有子包下的所有類如果含有@Component、@Controller、@Service、@Repository等注解的 話都會自動納入到Spring容器中,但是每個類都一個個加上注解,有時難免覺得繁瑣,其實Spring也為我們提供了自動為類加上注解的功能。配置如 下:

<!-- 啟用spring mvc 注解 --><context:annotation-config /><!-- 設置使用注解的類所在的包 --><context:component-scan base-package="com.lmb.**.rest,com.lmb..server.http,com.lmb.**.mvc"><context:include-filter type="annotation"expression="org.springframework.stereotype.Controller" /><context:exclude-filter type="annotation"expression="org.springframework.stereotype.Service" /></context:component-scan>

com.lmb..rest,com.lmb.hollyuniproxy.server.http,com.lmb..mvc包下的類都為使用注解的類。

要特別注意其中的context:include-filter標簽和context:exclude-filter標簽:
context:include-filter
此標簽的含義是:在其掃描到的所有包下的類,全部自動加上注解并納入Spring容器中。
比如下面這個類:

public class InterfaceVisitService implements IInterfaceVisitService { //…… }

那么該標簽等于為InterfaceVisitService 類加上@Component注解,且bean的id為interfaceVisitService。

@Component(“interfaceVisitService”) public class InterfaceVisitService implements IInterfaceVisitService { //…… }

context:exclude-filter
此標簽的含義是:排除掃描到的所有類,不納入Spring容器中。
但需要注意的是,采用自動注入,類名不能相同(即便包名不同),因為自動注入時,id與類名相同,所以如果兩個類名一樣的話,會因為Bean的id相同而報錯。如果類名一定要相同的話,只能是其中一個類,手動加上注解并將名稱改為其他。

總結

以上是生活随笔為你收集整理的【Spring学习】spring注解自动注入bean的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。