javascript
【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容器中。
比如下面這個類:
那么該標簽等于為InterfaceVisitService 類加上@Component注解,且bean的id為interfaceVisitService。
@Component(“interfaceVisitService”) public class InterfaceVisitService implements IInterfaceVisitService { //…… }context:exclude-filter
此標簽的含義是:排除掃描到的所有類,不納入Spring容器中。
但需要注意的是,采用自動注入,類名不能相同(即便包名不同),因為自動注入時,id與類名相同,所以如果兩個類名一樣的話,會因為Bean的id相同而報錯。如果類名一定要相同的話,只能是其中一個類,手動加上注解并將名稱改為其他。
總結
以上是生活随笔為你收集整理的【Spring学习】spring注解自动注入bean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【echarts】echarts开发流程
- 下一篇: java.io.CharConversi