最近在做一个项目,有一个需求,是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());
}
}
}