spring配置事物

方法一:通過切面配置

1、配置數據源

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    	<property name="url" value="jdbc:mysql://192.168.0.88:3306/product123"></property>
    	<property name="username" value="root"></property>
    	<property name="defaultAutoCommit" value="false"/>
    	<property name="password" value="x5"></property>
</bean> 

2、配置事物管理器

<bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" /> 
</bean>  

事物管理器的 dataSource屬性引用了數據源。

3、配置事物的通知

    <tx:advice id="txAdvice" transaction-manager="transactionManager" >
    	   <tx:attributes>
    	 	<tx:method name="*"  isolation="READ_COMMITTED" propagation="REQUIRED"/>
    	 </tx:attributes> 
    </tx:advice>

通知的transactionManager屬性引用了事物管理器,在<tx:attributes/>標籤下可以定義傳播行爲隔離級別等信息。

4、把通知和切點關聯

<aop:config>
    <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service..*(..))"/>
</aop:aspect>

通過標籤<aop:advisor/>的pointcut屬性指明事物要用在哪些類的哪些方法上。

 

方法二:通過註解配置

第一步和第二步同方法一

第三步:啓動註解驅動

<tx:annotation-driven  transaction-manager="transactionManager" />

第四補:給服務類加上事物註解@Transactional

@Transactional(isolation=Isolation.READ_COMMITTED)
@Service
@Scope(ConfigurableBeanFactory .SCOPE_PROTOTYPE)
public class EmployeeServiceImpl implements EmployeeService{

	@Autowired
	EmployeeDao employeeDao;
	public void selectEmployee(Employee employee) {
		employeeDao.selectEmployee(employee);
		System.out.println("服務調用。。。");
	}

}

@Transactional可以配置隔離級別,傳播行爲,回滾等屬性

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章