一个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个回答

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问