在一個(gè)稍大的項(xiàng)目中,通常會(huì)有上百個(gè)組件,如果這些組件采用xml的bean定義來(lái)配置,顯然會(huì)增加配置文件的體積,查找以及維護(hù)起來(lái)也不太方便。Spring2.5為我們引入了組件自動(dòng)掃描機(jī)制,他可以在類路徑底下尋找標(biāo)注了@Component,@Service,@Controller,@Repository注解的類,并把這些類納入進(jìn)spring容器中管理。它的作用和在xml文件中使用bean節(jié)點(diǎn)配置組件時(shí)一樣的。要使用自動(dòng)掃描機(jī)制,我們需要打開以下配置信息
- <?xml
version= "1.0"encoding= "UTF-8"?> "http://www.springframework.org/schema/beans"<beans xmlns= xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"xmlns:context= "http://www.springframework.org/schema/context"xsi:schemaLocation= "http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ - >
-
- <context:component-scan
base- package=”com.eric.spring”> - </beans>
- 其中base-package為需要掃描的包(含所有子包)
@Service用于標(biāo)注業(yè)務(wù)層組件,@Controller用于標(biāo)注控制層組件(如struts中的action),@Repository用于標(biāo)注數(shù)據(jù)訪問組件,即DAO組件,而@Component泛指組件,當(dāng)組件不好歸類的時(shí)候,我們可以使用這個(gè)注解進(jìn)行標(biāo)注。 - @Service
public class VentorServiceImpl implementsiVentorService { - }
@Repository public class VentorDaoImpl implementsiVentorDao { - }
getBean的默認(rèn)名稱是類名(頭字母小寫),如果想自定義,可以 @Service(“aaaaa”)這樣來(lái)指定,這種bean默認(rèn)是單例的,如果想改變,可以使用@Service(“beanName”)@Scope(“prototype”)來(lái)改變。可以使用以下方式指定初始化方法和銷毀方法(方法名任意): @PostConstruct public void init() { - }
- @PreDestroy
public void destory() {