spring中的事务是经过aop来实现的,当咱们本身实现aop拦截的时候,会遇到跟spring的事务aop执行的前后顺序问题,好比说动态切换数据源的问题,若是事务在前,数据源切换在后,会致使数据源切换失效,因此就用到了Order(排序)这个关键字。spring
咱们能够经过在@AspectJ的方法中实现org.springframework.core.Ordered这个接口来定义order的顺序,order的值越小,说明越先被执行。示例代码以下:bash
/**
* 多数据源,切面处理类
*
* @author 文希
* @create 2019-04-25 15:10
**/
@Aspect // 开启切面
@Component
public class DataSourceAspect implements Ordered { // 时间Ordered接口
private Logger logger = LoggerFactory.getLogger(getClass());
// 拦截DataSource下面的类
@Pointcut("@annotation(com.hm.admin.datasources.annotation.DataSource)")
public void dataSourcePointCut() {
}
@Around("dataSourcePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
DataSource ds = method.getAnnotation(DataSource.class);
if (null == ds) {
DynamicDataSource.setDataSource(DataSourceNames.FIRST);
logger.debug("set datasource is " + DataSourceNames.FIRST);
}
else {
DynamicDataSource.setDataSource(ds.name());
logger.debug("set datasource is " + ds.name());
}
try {
return point.proceed();
} finally {
DynamicDataSource.clearDataSource();
logger.debug("clean datasource");
}
}
@Override
public int getOrder() {
return 1;
}
}
复制代码
在事务配置的地方也配置order字段,代码以下: 《注解方式配置事务》ide
<tx:annotation-driven transaction-manager="transactionManager" order="2"/>
复制代码
这样就实现了咱们本身写的aop在事务介入以前就执行了。ui