代码实现
1import java.util.Collections; 2import java.util.HashMap; 3import java.util.Map; 4 5import org.aspectj.lang.annotation.Aspect; 6import org.springframework.aop.Advisor; 7import org.springframework.aop.aspectj.AspectJExpressionPointcut; 8import org.springframework.aop.support.DefaultPointcutAdvisor; 9import org.springframework.beans.factory.annotation.Autowired; 10import org.springframework.context.annotation.Bean; 11import org.springframework.context.annotation.Configuration; 12import org.springframework.transaction.PlatformTransactionManager; 13import org.springframework.transaction.TransactionDefinition; 14import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource; 15import org.springframework.transaction.interceptor.RollbackRuleAttribute; 16import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute; 17import org.springframework.transaction.interceptor.TransactionAttribute; 18import org.springframework.transaction.interceptor.TransactionInterceptor; 19 20/** 21 * @Title: TxAdviceInterceptor.java 22 * @Package com.cloud.aop 23 * @Description: 24 * @author ybwei 25 * @date 2018年9月3日 上午10:37:31 26 * @version V1.0 27 */ 28@Aspect 29@Configuration 30public class TxAdviceInterceptor { 31 private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.cloud.serviceImpl.*.*(..))"; 32 @Autowired 33 private PlatformTransactionManager transactionManager; 34 35 @Bean 36 public TransactionInterceptor txAdvice() { 37 NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource(); 38 /* 当前没有事务:只有select,非事务执行;有update,insert,delete操作,自动提交; 39 * 当前有事务:如果有update,insert,delete操作,支持当前事务 */ 40 RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute(); 41 readOnlyTx.setReadOnly(true); 42 readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); 43 /* 当前存在事务就使用当前事务,当前不存在事务就创建一个新的事务 */ 44 RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute(); 45 requiredTx.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class))); 46 requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); 47 // requiredTx.setTimeout(TX_METHOD_TIMEOUT); 48 Map<String, TransactionAttribute> txMap = new HashMap<>(); 49 txMap.put("add*", requiredTx); 50 txMap.put("save*", requiredTx); 51 txMap.put("insert*", requiredTx); 52 txMap.put("update*", requiredTx); 53 txMap.put("delete*", requiredTx); 54 txMap.put("get*", readOnlyTx); 55 txMap.put("query*", readOnlyTx); 56 source.setNameMap(txMap); 57 TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager, source); 58 return txAdvice; 59 } 60 61 @Bean 62 public Advisor txAdviceAdvisor(TransactionInterceptor txAdvice) { 63 AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); 64 pointcut.setExpression(AOP_POINTCUT_EXPRESSION); 65 return new DefaultPointcutAdvisor(pointcut, txAdvice); 66 } 67}