前面的例子咱們都是使用XML的bean定義來配置組件。在一個稍大的項目中,
一般會有上百個組件,若是這些這組件採用xml的bean定義來配置,顯然會
增長配置文件的體積,查找及維護起來也不太方便。spring2.5爲咱們引入
了組件自動掃描機制,他能夠在類路徑底下尋找標註了
@Component、@Service、@Controller、@Repository註解的類,並把這些類
歸入進spring容器中管理。它的做用和在xml文件中使用bean節點配置組件
是同樣的。要使用自動掃描機制,咱們須要打開如下配置信息:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="cn.itcast"/>
</beans>
其中base-package爲須要掃描的包(含子包)。
@Service用於標註業務層組件、
@Controller用於標註控制層組件(如struts中的action)、
@Repository用於標註數據訪問組件,即DAO組件。
而@Component泛指組件,當組件很差歸類的時候,咱們能夠使用這個註解進行標註。spring
舉例說明:
spa
@Servicecomponent
public class OrderService{xml
}it
@Repositoryio
public class OrderDao{ast
}class
@Controller容器
public class OrderAction extends Action{配置
}