spring声明式事物管理
事物的管理在程序或项目中是比较重要的处理,spring对于事物的管理配置也很重要,这里以spring集成hibernate举例子,spring事物管理,有两种,一种是annotation的方式,一种是通过xml配置的方式实现,首先annotation的配置,先在xml里面配置命名空间,数据源,sessionFactory配置,然后加入,事物的bean,配置txManager,如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"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.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <context:annotation-config/> <context:component-scan base-package="*"/> <tx:annotation-driven transaction-manager="txManager"/> <bean id="mappings" value="classpath:jdbc.properties"></property> </bean> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <bean id="sessionFactory" ref="dataSource"/><property name="annotatedClasses"><list><value>cn.com.test.model.User</value></list></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop><prop key="hibernate.show_sql">true</prop></props></property></bean><bean id="txManager" ref="sessionFactory" /></bean></beans><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="update" read-only="true"/><tx:method name="save"/></tx:attributes></tx:advice><aop:config><aop:pointcut id="UserService" expression="execution(* cn.com.test.service..*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="UserService"/></aop:config>