AOP的配置稍顯復雜,通過
@Transactional
注解,同樣可以實現:
1. 在需要事務的類或方法上加 @Transactional :
?? 如果是類上加注解,該類的所有public方法都會應用事務
?? 如果是方法上加注解,該方法會應用事務。
?? 在接口上加注解有風險,如果使用CGLIB(類代理)將不會啟用事務。
2. 開啟注解事務開關: <tx:annotation-driven />
FruitShop實現:
beans-fruitshop-@.xml文件:
測試類和之前的類似:
附:
Spring底層也是通過AOP來實現對@Transactional注解事務的支持:
1. 在需要事務的類或方法上加 @Transactional :
?? 如果是類上加注解,該類的所有public方法都會應用事務
?? 如果是方法上加注解,該方法會應用事務。
?? 在接口上加注解有風險,如果使用CGLIB(類代理)將不會啟用事務。
2. 開啟注解事務開關: <tx:annotation-driven />
FruitShop實現:
public class AnnotationTxFruitShop extends JdbcDaoSupport implements FruitShop { @Transactional // 可以設置傳播級別、隔離級別、超時、只讀、回滾策略 @Override public boolean purchase(int fruitId, String userName, int count) { // 此處和系列之四的AopTxFruitShop代碼相同 } }
beans-fruitshop-@.xml文件:
<tx:annotation-driven transaction-manager="txManager" /> <bean id="annotationTxFruitShop" class="com.john.tx.service.impl.AnnotationTxFruitShop"> <property name="dataSource" ref="dataSource" /> </bean> <!-- dataSource, txManager和之前的相同 -->
測試類和之前的類似:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/beans-fruitshop-@.xml" }) public class AnnotationTxFruitShopTest { @Resource(name = "annotationTxFruitShop") FruitShop annotationTxFruitShop; @Test public void test() { ... } }
附:
Spring底層也是通過AOP來實現對@Transactional注解事務的支持:

更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
