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