天天看点

Spring声明式事务配置管理方法

环境配置

  项目使用ssh架构,现在要添加spring事务管理功能,针对当前环境,只需要添加spring2.0aop类库即可。添加方法:

  点击项目右键->buildpath->addlibrarys:

Spring声明式事务配置管理方法

  打开addlibraries对话框,然后选定myeclipselibraries:

Spring声明式事务配置管理方法

  点击next,找到spring2.0aoplibraries并勾选上,点击finsh即可。

Spring声明式事务配置管理方法

  如果在项目里面能看到下面的库文件,说明已经安装成功。

Spring声明式事务配置管理方法

  事务配置

  首先在/web-inf/applicationcontext.xml添加以下内容:

<!--配置事务管理器-->

<beanid="transactionmanager"class="org.springframework.orm.hibernate3.hibernatetransactionmanager">

<propertyname="sessionfactory">

<refbean="mysessionfactory"/>

</property>

</bean>

注:这是作为公共使用的事务管理器bean。这个会是事先配置好的,不需各个模块各自去配。

  下面就开始配置各个模块所必须的部分,在各自的applicationcontext-xxx-beans.xml配置的对于事务管理的详细信息。

  首先就是配置事务的传播特性,如下:

<!--配置事务传播特性-->

<tx:adviceid="testadvice"transaction-manager="transactionmanager">

<tx:attributes>

<tx:methodname="save*"propagation="required"/>

<tx:methodname="del*"propagation="required"/>

<tx:methodname="update*"propagation="required"/>

<tx:methodname="add*"propagation="required"/>

<tx:methodname="find*"propagation="required"/>

<tx:methodname="get*"propagation="required"/>

<tx:methodname="apply*"propagation="required"/>

</tx:attributes>

</tx:advice>

<!--配置参与事务的类-->

<aop:config>

<aop:pointcutid="alltestservicemethod"expression="execution(*com.test.testada.test.model.service.*.*(..))"/>

<aop:advisorpointcut-ref="alltestservicemethod"advice-ref="testadvice"/>

</aop:config>

  需要注意的地方:

  (1)advice(建议)的命名:由于每个模块都会有自己的advice,所以在命名上需要作出规范,初步的构想就是模块名+advice(只是一种命名规范)。

  (2)tx:attribute标签所配置的是作为事务的方法的命名类型。

  如<tx:methodname="save*"propagation="required"/>

  其中*为通配符,即代表以save为开头的所有方法,即表示符合此命名规则的方法作为一个事务。

  propagation="required"代表支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。

  (3)aop:pointcut标签配置参与事务的类,由于是在service中进行数据库业务操作,配的应该是包含那些作为事务的方法的service类。

  首先应该特别注意的是id的命名,同样由于每个模块都有自己事务切面,所以我觉得初步的命名规则因为all+模块名+servicemethod。而且每个模块之间不同之处还在于以下一句:

  expression="execution(*com.test.testada.test.model.service.*.*(..))"

  其中第一个*代表返回值,第二*代表service下子包,第三个*代表方法名,“(..)”代表方法参数。

  (4)aop:advisor标签就是把上面我们所配置的事务管理两部分属性整合起来作为整个事务管理。

  图解:

Spring声明式事务配置管理方法

最新内容请见作者的github页:http://qaseven.github.io/