spring core包中的order作用

spring中的事务是通过aop来实现的,当我们自己实现aop拦截的时候,会遇到跟spring的事务aop执行的先后顺序问题,比如说动态切换数据源的问题,如果事务在前,数据源切换在后,会导致数据源切换失效,所以就用到了Order(排序)这个关键字。

我们可以通过在@AspectJ的方法中实现org.springframework.core.Ordered这个接口来定义order的顺序,order的值越小,说明越先被执行。示例代码如下:

/**
 * 多数据源,切面处理类
 *
 * @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字段,代码如下: 《注解方式配置事务》

<tx:annotation-driven transaction-manager="transactionManager" order="2"/>
复制代码

这样就实现了我们自己写的aop在事务介入之前就执行了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值