1. 程式人生 > >37--Spring 基於tx標籤和基於@Transactional註解的宣告式事物介紹

37--Spring 基於tx標籤和基於@Transactional註解的宣告式事物介紹

上一節中已經對Spring事物的一些基本概念和核心介面做了簡介,並且演示了程式設計式事物實現,接下來介紹Spring中的另一種事物管理實現–宣告式事物

其底層建立在 AOP 的基礎之上,對方法前後進行攔截,然後在目標方法開始之前建立或者加入一個事務,在執行完目標方法之後根據執行情況提交或者回滾事務。通過宣告式事物,無需在業務邏輯程式碼中摻雜事務管理的程式碼,只需在配置檔案中做相關的事務規則宣告(或通過等價的基於標註的方式),便可以將事務規則應用到業務邏輯中。

宣告式事物的實現方式有很多種,例如基於TransactionInterceptor、TransactionProxyFactoryBean、tx標籤、Transactional註解等等。下面我們演示一下tx標籤和Transactional的使用,為接下來的原始碼分析做好準備。

1.基於tx標籤的宣告式事物
  • bean
package com.lyc.cn.v2.day08;

/**
 * 賬戶介面
 * @author: LiYanChao
 * @create: 2018-11-07 18:38
 */
public interface AccountServiceImp {
	void save() throws RuntimeException;
}
package com.lyc.cn.v2.day08;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 賬戶介面實現
 * @author: LiYanChao
 * @create: 2018-11-07 18:39
 */
public class AccountServiceImpl implements AccountServiceImp { private JdbcTemplate jdbcTemplate; private static String insert_sql = "insert into account(balance) values (100)"; @Override public void save() throws RuntimeException { System.out.println("==開始執行sql"); jdbcTemplate.update(insert_sql)
; System.out.println("==結束執行sql"); System.out.println("==準備丟擲異常"); throw new RuntimeException("==手動丟擲一個異常"); } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } }
  • 配置檔案
<?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:tx="http://www.springframework.org/schema/tx"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

	<!--事物管理器-->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!--資料來源-->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/my_test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
		<property name="username" value="root"/>
		<property name="password" value="[email protected]"/>
	</bean>

	<!--jdbcTemplate-->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!--業務bean-->
	<bean id="accountService" class="com.lyc.cn.v2.day08.AccountServiceImpl">
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
	</bean>

	<!--tx標籤配置-->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="query*" propagation="REQUIRED"/>
			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!--aop配置-->
	<aop:config>
		<aop:pointcut id="txPointcut" expression="execution(* com.lyc.cn.v2.day08..*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
	</aop:config>

</beans>
  • 測試類及結果
@Test
public void test2() {
    // 基於tx標籤的宣告式事物
    ApplicationContext ctx = new ClassPathXmlApplicationContext("v2/day08.xml");
    AccountServiceImp studentService = ctx.getBean("accountService", AccountServiceImp.class);
    studentService.save();
}
==開始執行sql
==結束執行sql
==準備丟擲異常

java.lang.RuntimeException: ==手動丟擲一個異常

	at com.lyc.cn.v2.day08.AccountServiceImpl.save(AccountServiceImpl.java:24)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)

測試方法中手動丟擲了一個異常,Spring會自動回滾事物,檢視資料庫可以看到並沒有新增記錄。

2.基於@Transactional註解的宣告式事物
  • bean
package com.lyc.cn.v2.day09;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 賬戶介面
 * @author: LiYanChao
 * @create: 2018-11-07 18:38
 */
@Transactional(propagation = Propagation.REQUIRED)
public interface AccountServiceImp {
	void save() throws RuntimeException;
}
package com.lyc.cn.v2.day09;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 賬戶介面實現
 * @author: LiYanChao
 * @create: 2018-11-07 18:39
 */
public class AccountServiceImpl implements AccountServiceImp {

	private JdbcTemplate jdbcTemplate;

	private static String insert_sql = "insert into account(balance) values (100)";


	@Override
	public void save() throws RuntimeException {
		System.out.println("==開始執行sql");
		jdbcTemplate.update(insert_sql);
		System.out.println("==結束執行sql");

		System.out.println("==準備丟擲異常");
		throw new RuntimeException("==手動丟擲一個異常");
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}
  • 配置檔案
<?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:tx="http://www.springframework.org/schema/tx"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!--開啟tx註解-->
	<tx:annotation-driven transaction-manager="transactionManager"/>

	<!--事物管理器-->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!--資料來源-->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/my_test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
		<property name="username" value="root"/>
		<property name="password" value="[email protected]"/>
	</bean>

	<!--jdbcTemplate-->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"/>
	</bean>

	<!--業務bean-->
	<bean id="accountService" class="com.lyc.cn.v2.day09.AccountServiceImpl">
		<property name="jdbcTemplate" ref="jdbcTemplate"/>
	</bean>

</beans>
  • 測試及結果
package com.lyc.cn.v2.day09;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author: LiYanChao
 * @create: 2018-11-07 18:45
 */
public class MyTest {

	@Test
	public void test1() {
		// 基於tx標籤的宣告式事物
		ApplicationContext ctx = new ClassPathXmlApplicationContext("v2/day09.xml");
		AccountServiceImp studentService = ctx.getBean("accountService", AccountServiceImp.class);
		studentService.save();
	}
}
==開始執行sql
==結束執行sql
==準備丟擲異常

java.lang.RuntimeException: ==手動丟擲一個異常

	at com.lyc.cn.v2.day09.AccountServiceImpl.save(AccountServiceImpl.java:24)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)

測試方法中手動丟擲了一個異常,Spring會自動回滾事物,檢視資料庫可以看到並沒有新增記錄。

3.總結

以上兩種方式都比較簡單,只要配置正確就可以,當然很多細節並沒有分析到,感興趣的同學可以參考Spring的官方文件檢視更多的細節化的配置,接下來我們就分析基於@Transactional註解的宣告式事物的的原始碼實現。