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

一个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
    已采纳

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

    点赞 打赏 评论

相关推荐 更多相似问题