struts2 spring hibernate的整合

集成 struts2 spring hibernate的实例

集成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的集成。

 

一:配置struts2。

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的集成。

 

二:配置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配置


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值