江蘇520
集成struts,spring,hibernate時(shí),對(duì)于初學(xué)者來(lái)說(shuō)最大的麻煩就其繁瑣的xml配置文件。現(xiàn)在三者都對(duì)基于注解的配置提供了良好的支持。在struts2中,使用convent plugin,得益于annotation和規(guī)約,配置過(guò)程得以大大減少。在spring2.5也可以使用@Autowired,進(jìn)行注入,使用@Controller,@Service,@Repository注解,自動(dòng)定義bean,還支持annotation風(fēng)格的聲明式事務(wù)支持,以及aspectJ類似的AOP。hibernate也可以使用JPA標(biāo)準(zhǔn)注解定義實(shí)體描述,避免使用mapping文件。
當(dāng)然,對(duì)于annotation和xml風(fēng)格的配置,誰(shuí)更好,更多依賴個(gè)人興趣。但使用annotation確實(shí)減少了很多配置工作量。本文采用annotation風(fēng)格的配置,以TaskList為例子講解struts2 spring hibernate的集成。項(xiàng)目文件見(jiàn)附件。
首先在web.xml文件中配置filter
然后在classpath中創(chuàng)建struts.xml配置文件。
struts.devMode屬性,配置啟用調(diào)試,將有更多的錯(cuò)誤信息輸出,便于排錯(cuò)。struts.convention.default.parent.package屬性,指定使用注解標(biāo)注的控制器的默認(rèn)包。可以在這個(gè)默認(rèn)包中配置全局信息。
struts.convention.package.locators屬性,為查找控制器包路徑的關(guān)鍵字。如com.mycompany.action,com.mycompany.action.user,都會(huì)被struts2掃描。里面有繼承至Action的類,或類名以Action結(jié)尾的類,都會(huì)做為Action處理。
<default-action-ref name="index" />指定了默認(rèn)action,如果指定的action不存在則訪問(wèn)該action。
把struts2-spring-plugin-2.1.6.jar添加到classpath中,struts2會(huì)自動(dòng)掃描struts-plugin.xml文件,該文件自動(dòng)注冊(cè)了com.opensymphony.xwork2.ObjectFactory,完成和spring的集成。
在web.xml中加入ContextLoaderListener,用以啟動(dòng)spring容器。用contextConfigLocation指定spring配置文件路徑,可以使用*通配符結(jié)尾。
配置applicationContext.xml
<context:component-scan />指定Bean掃描的包,多個(gè)包逗號(hào)隔開,任何標(biāo)注了@Component,@Controller,@Service,@Repository的類,都會(huì)被自動(dòng)識(shí)別為bean。
<aop:aspectj-autoproxy />聲明aspectj動(dòng)態(tài)代理,啟用注解驅(qū)動(dòng)的aspectj配置。
<tx:annotation-driven />啟用注解驅(qū)動(dòng)的聲明事務(wù)支持。
然后定義了sessionFactory和transactionManager,hibernateTemplate用來(lái)注入到Dao中,取代繼承的方式使用spring對(duì)hibernate的集成支持。
hibernate配置獨(dú)立配置,方便修改。
posted on 2009-05-14 17:40 江蘇520 閱讀(4079) 評(píng)論(0) 編輯 收藏
Powered by: BlogJava Copyright © 江蘇520