1. 程式人生 > >【Spring學習】spring註解自動注入bean

【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相同而報錯。如果類名一定要相同的話,只能是其中一個類,手動加上註解並將名稱改為其他。