cm-cloud/cloud-common/src/main/java/com/cm/common/config/TransactionConfig.java
2019-08-27 11:20:57 +08:00

76 lines
2.8 KiB
Java

package com.cm.common.config;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* @ClassName: GlobalTransactionConfig
* @Description: 全局事务处理
* @Author: WangGeng
* @Date: 2019/2/26 4:18 PM
* @Version: 1.0
**/
@Aspect
@Configuration
public class TransactionConfig {
@Autowired
private PlatformTransactionManager transactionManager;
/**
* 事务拦截器
*
* @return
*/
@Bean
public TransactionInterceptor txAdvice() {
DefaultTransactionAttribute required = new DefaultTransactionAttribute();
required.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
DefaultTransactionAttribute readOnly = new DefaultTransactionAttribute();
readOnly.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
readOnly.setReadOnly(true);
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
source.addTransactionalMethod("add*", required);
source.addTransactionalMethod("save*", required);
source.addTransactionalMethod("delete*", required);
source.addTransactionalMethod("remove*", required);
source.addTransactionalMethod("update*", required);
source.addTransactionalMethod("edit*", required);
source.addTransactionalMethod("exec*", required);
source.addTransactionalMethod("set*", required);
source.addTransactionalMethod("login", required);
source.addTransactionalMethod("get*", readOnly);
source.addTransactionalMethod("query*", readOnly);
source.addTransactionalMethod("find*", readOnly);
source.addTransactionalMethod("list*", readOnly);
source.addTransactionalMethod("count*", readOnly);
source.addTransactionalMethod("is*", readOnly);
return new TransactionInterceptor(transactionManager, source);
}
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution (* com.cm..*.service..*(..))");
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
}