【Spring】—AOP之AspectJ註解方式實現聲明式事務管理

前言

這回來說下註解方式的聲明式事務管理。

正文

Demo

1、引入相關的jar包
這裏寫圖片描述【Spring】—AOP之AspectJ註解方式實現聲明式事務管理

2、引入AOP約束
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.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 ">
</beans>

3、準備目標對象
public interface AccountService {
//轉賬方法
void transfer(Integer from,Integer to,Double money);
}
/****/
public class AccountServiceImpl implements AccountService {

private AccountDao ad;
public void setAd(AccountDao ad) {
    this.ad = ad;
}

@Override
//轉賬方法 
public void transfer( Integer from, Integer to, Double money){
            //減錢
            ad.decreaseMoney(from, money);
            //異常代碼
            int i = 1/0;  
            //加錢
            ad.increaseMoney(to, money);
        }

}

4、開啓註解管理事務

**5、使用註解** 在使用事務的類或者方法上加一個註解:@Transactional @Override //轉賬方法 @Transactional(isolation =Isolation.REPEATABLE_READ,propagation= Propagation.REQUIRED,readOnly= false) public void transfer( Integer from, Integer to, Double money){ //減錢 ad.decreaseMoney(from, money); int i = 1/0; //加錢 ad.increaseMoney(to, money); } **6、測試** @RunWith(SpringJUnit4Cla***unner.class) @ContextConfiguration("classpath:applicationContext2.xml") public class Demo2 { @Resource(name = "accountService") private AccountService as; @Test public void fun1(){ as.transfer(1, 2, 100d); } 結果: A和B賬戶的錢都沒有發生變化,事務註解成功! 上面這種是AspectJ的方式,Aspect 是一套獨立的面向切面編程的解決方案。Spring 集成了與Aspect 5 一樣的註解,並使用了AspectJ 來做切入點的解析和匹配。 #### **SpringAOP 中選擇@AspectJ 還是Schema (XML)?** @AspectJ 是靜態編譯方式,Schema AOP 是動態編譯方式 XML風格有兩個缺點:1、因爲需求被分割到了通知類的聲明中和xml配置文件中,他不能完全將需求實現的地方封裝到一個位置,違背了DRY原則。當使用 @AspectJ 風格時就只有一個獨立的模塊-切面,信息被封裝了;2、xml風格同@Asepect風格所能表達的內容有更多的限制,僅支持“singleton”切面實例模型,並且不能在xml中組合命名連接點的聲明,@AspectJ風格支持其他的實例模型以及更豐富的連接點組合。 @Aspect 切面能被Spring AOP 和 AspectJ兩者都能理解。 # **總結** 以上介紹了AOP註解方式實現聲明式事務,相對於XML方式,代碼簡潔了,註解方式越來越流行,感謝您的閱讀!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章