Spring 2.5 中除了提供 @Component 注釋外,還定義了幾個(gè)擁有特殊語義的注釋,它們分別是:@Repository歹苦、@Service 和 @Controller青伤。
在目前的 Spring 版本中,這 3 個(gè)注釋和 @Component 是等效的殴瘦,但是從注釋類的命名上狠角,很容易看出這 3 個(gè)注釋分別和持久層、業(yè)務(wù)層和控制層(Web 層)相對應(yīng)蚪腋。
雖然目前這3 個(gè)注釋和 @Component 相比沒有什么新意丰歌,但 Spring 將在以后的版本中為它們添加特殊的功能。
所以屉凯,如果 Web 應(yīng)用程序采用了經(jīng)典的三層分層結(jié)構(gòu)的話立帖,最好在持久層、業(yè)務(wù)層和控制層分別采用上述注解對分層中的類進(jìn)行注釋悠砚。
@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)注绑咱。
[java]?view plain?copy
@Service??
public?class?VentorServiceImpl?implements?iVentorService?{?????
}??
@Repository??
public?class?VentorDaoImpl?implements?iVentorDao?{???
}??
在一個(gè)稍大的項(xiàng)目中,如果組件采用xml的bean定義來配置枢泰,顯然會(huì)增加配置文件的體積描融,查找以及維護(hù)起來也不太方便。?
Spring2.5為我們引入了組件自動(dòng)掃描機(jī)制宗苍,他在類路徑下尋找標(biāo)注了上述注解的類稼稿,并把這些類納入進(jìn)spring容器中管理。
它的作用和在xml文件中使用bean節(jié)點(diǎn)配置組件時(shí)一樣的讳窟。要使用自動(dòng)掃描機(jī)制让歼,我們需要打開以下配置信息:
代碼
[html]?view plain?copy
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">???
?????
1.component-scan標(biāo)簽?zāi)J(rèn)情況下自動(dòng)掃描指定路徑下的包(含所有子包),將帶有@Component丽啡、@Repository谋右、@Service、@Controller標(biāo)簽的類自動(dòng)注冊到spring容器补箍。對標(biāo)記了 Spring's @Required改执、@Autowired、JSR250's @PostConstruct坑雅、@PreDestroy辈挂、@Resource、JAX-WS's @WebServiceRef裹粤、EJB3's @EJB终蒂、JPA's @PersistenceContext、@PersistenceUnit等注解的類進(jìn)行對應(yīng)的操作使注解生效(包含了annotation-config標(biāo)簽的作用)。
getBean的默認(rèn)名稱是類名(頭字母小寫)拇泣,如果想自定義噪叙,可以@Service(“aaaaa”)這樣來指定。
這種bean默認(rèn)是“singleton”的霉翔,如果想改變睁蕾,可以使用@Scope(“prototype”)來改變。
可以使用以下方式指定初始化方法和銷毀方法:
[java]?view plain?copy
@PostConstruct??
public?void?init()?{???
}???
@PreDestroy??
public?void?destory()?{???
}???
注入方式:
把DAO實(shí)現(xiàn)類注入到action的service接口(注意不要是service的實(shí)現(xiàn)類)中债朵,注入時(shí)不要new 這個(gè)注入的類子眶,因?yàn)閟pring會(huì)自動(dòng)注入,如果手動(dòng)再new的話會(huì)出現(xiàn)錯(cuò)誤序芦,
然后屬性加上@Autowired后不需要getter()和setter()方法壹店,Spring也會(huì)自動(dòng)注入。
在接口前面標(biāo)上@Autowired注釋使得接口可以被容器注入芝加,如:
[java]?view plain?copy
@Autowired??
@Qualifier("chinese")??
private?Man?man;???
當(dāng)接口存在兩個(gè)實(shí)現(xiàn)類的時(shí)候必須使用@Qualifier指定注入哪個(gè)實(shí)現(xiàn)類,否則可以省略射窒,只寫@Autowired藏杖。