在繼續講解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中的。
新聞熱點
疑難解答