Spring自動掃描+注解注入


一、基本使用
可通過在配置文件content-xml中設置如下,即可使用spring組件注解,可以實現bean的自動載入。
<context:annotation-config />
<!-- 配置容器資源掃描的包 -->
<context:component-scan base-package="com.csair.baggage"></context:component-scan>
<context:annotation-config /> 聲明可以通過注解的方式,實現bean的初始化。
base-package 表明這個包以及它的子包都是在掃描的范圍。只要有出現@Component,@Service,@Controller,@Repository都是會自動生成Bean的,如果不指定id的話,
一般都是以類名作為bean的名字。
@Service,@Controller,@Repository標注的是不同功能的bean,是@Component的細化。是為了更好的配置我們的bean,方便我們的使用。
@Repository對應了持久化層
@Service對應了服務層
@Service對應了表現層
二、其他標簽
<context:component-scan>提供兩個子標簽:<context:include-filter><context:exclude-filter>各代表引入和排除的過濾。
代碼如下:
 <context:component-scan base-package="com.csair"> 
   <context:exclude-filter type="annotation" 
    expression="org.springframework.stereotype.Controller"/> 
</context:component-scan>  
表示掃描com.csair包,含有Controller注解的就注冊。用exclude-filter標簽的就表示除了這個,其他的注解都會掃描。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM