DreamGoBell 2017-02-09 09:00 采纳率: 100%
浏览 4968
已采纳

一个Spring Boot Aop扫描@Transaction注解的问题

最近在做一个项目,有一个需求,是service层添加了@Transaction注解的读方法就切换到从库.
现在问题是这样:项目Service层是有写接口层和实现层的,只有两处都加上@Transaction注解,Aop才能进到我的方法,我是想只加在Service实现层的方法上,不知道是什么地方的问题,有没有朋友碰到过类似的问题?望解答

下面上代码:

<aop:config>
    <aop:pointcut id="appService"
        expression="execution(* com.csdn.parking..*Service*.*(..))" />
    <aop:advisor advice-ref="txAdvice2" pointcut-ref="appService" />
    <aop:aspect ref="switchDataSourceHandler" order="1">
        <aop:before method="switchDataSource"
            pointcut="@annotation(org.springframework.transaction.annotation.Transactional)" />
    </aop:aspect>
</aop:config>





public class SwitchDataSourceHandler {

private static final Logger log = LoggerFactory.getLogger(SwitchDataSourceHandler.class);

public void switchDataSource(JoinPoint joinPoint) {
    try {
        String className = joinPoint.getTarget().getClass().getName();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Transactional txAnnotation = method.getAnnotation(Transactional.class);
        if (txAnnotation != null) {
            final boolean isReadOnly = txAnnotation.readOnly();
            log.info("[Aop SwitchDataSourceHandler] ClassName:" + className + "  MothodName:"
                    + method.getName() + "  IsReadOnly:" + isReadOnly);
            log.info("[Aop SwitchDataSourceHandler] Current datasource:"
                    + ContextHolder.getDbType().toString());
            if (ContextHolder.getDbType() == DBType.abcDataSource) {
                ContextHolder.setDbType(DBType.abcDataSourceSlave);
                log.info("[Aop SwitchDataSourceHandler] Switch datasource to abcDataSourceSlave");
            } else if (ContextHolder.getDbType() == DBType.zxcDataSource) {
                ContextHolder.setDbType(DBType.zxcDataSourceSlave);
                log.info("[Aop SwitchDataSourceHandler] Switch datasource to zxcDataSourceSlave");
            }
        }
    } catch (Exception e) {
        log.error("[Aop SwitchDataSourceHandler] Error occur in aop SwitchDataSourceHandler "
                + e.getMessage());
    }
}

}

  • 写回答

1条回答

  • DreamGoBell 2017-02-10 01:01
    关注

    没有大神吗?没有大神吗?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决