[Spring Framework]學習筆記--@Component等stereotype的基礎


在繼續講解Spring MVC之前,需要說一下常用的幾個用來標記stereotype的annotation。

@Component,@Controller,@Repository,@Service。

這四個都在org.springframework.stereotype包下面,后面3個都屬於@Component。

可以理解為@Component是@Controller,@Repository,@Service的基類。

 

@Component是用來標記任何被Spring管理的組件。

@Controller用來標記presentation層(比如web controller)。

@Repository用來標記persistence層(比如DAO)。

@Service用來標記service層。

 

如果我們為自己class增加了這些annotation后,如果讓Spring自動找到這些class,並實現注冊呢?

需要在Spring的xml中用到<context:component-scan>元素, base-package是要掃描的包名。

<beans
    ...
    xmlns:context="http://www.springframework.org/schema/context"
    ...>
    <context:component-scan base-package="xxx.xxx"/>
</beans>

 

<context:component-scan>的使用,是默認激活<context:annotation-config>功能的。而<context:annotation-config>又是干啥的呢?

主要是為@Autowired服務的(換句話就是說,使Spring可以處理像@Autowired和@Configuration這樣的annotations),試想一下,如果沒有<context:annotation-config>, 我們需要在Spring的XML文件中去注冊每一個bean,

導致整個XML文件非常大,而且難以維護。現在用一行,就可以來實現注冊,簡單方便。

 

注意1:如果有了<context:component-scan>, 我們是不需要顯式的來定義<context:annotation-config>的。

注意2:<context:annotation-config>只搜索在同一個application context下的被annotation標記的beans。

舉個例子,就是如果<context:annotation-config>加在WebApplicationContext下,它只檢查在controller中被標記為Autowired的beans,不會檢查service中的。


免責聲明!

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



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