在一個稍大的項目中,通常會有上百個組件,如果這些組件采用xml的bean定義來配置,顯然會增加配置文件的體積,查找以及維護起來也不太方便。Spring2.5為我們引入了組件自動掃描機制,他可以在類路徑底下尋找標注了@Component,@Service,@Controller,@Repository注解的類,并把這些類納入進spring容器中管理。它的作用和在xml文件中使用bean節點配置組件時一樣的。要使用自動掃描機制,我們需要打開以下配置信息

 
  1. <?xml version="1.0" encoding="UTF-8" ?> <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"  
  2. >   
  3.   
  4. <context:component-scan base-package=”com.eric.spring”>    
  5. </beans>    
  6. 其中base-package為需要掃描的包(含所有子包) @Service用于標注業務層組件,@Controller用于標注控制層組件(如struts中的action),@Repository用于標注數據訪問組件,即DAO組件,而@Component泛指組件,當組件不好歸類的時候,我們可以使用這個注解進行標注。    
  7. @Service public class VentorServiceImpl implements iVentorService    
  8. @Repository public class VentorDaoImpl implements iVentorDao {   
  9. getBean的默認名稱是類名(頭字母小寫),如果想自定義,可以@Service(“aaaaa”)這樣來指定,這種bean默認是單例的,如果想改變,可以使用@Service(“beanName”) @Scope(“prototype”)來改變??梢允褂靡韵路绞街付ǔ跏蓟椒ê弯N毀方法(方法名任意): @PostConstruct public void init() {   
  10. }   
  11. @PreDestroy public void destory() {