DataSourceAspect.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.ruoyi.framework.aspectj;
  2. import java.util.Objects;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.aspectj.lang.annotation.Pointcut;
  7. import org.aspectj.lang.reflect.MethodSignature;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.core.annotation.AnnotationUtils;
  11. import org.springframework.core.annotation.Order;
  12. import org.springframework.stereotype.Component;
  13. import com.ruoyi.common.annotation.DataSource;
  14. import com.ruoyi.common.utils.StringUtils;
  15. import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
  16. /**
  17. * 多数据源处理
  18. *
  19. * @author ruoyi
  20. */
  21. @Aspect
  22. @Order(1)
  23. @Component
  24. public class DataSourceAspect {
  25. protected Logger logger = LoggerFactory.getLogger(getClass());
  26. @Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)"
  27. + "|| @within(com.ruoyi.common.annotation.DataSource)")
  28. public void dsPointCut() {
  29. }
  30. @Around("dsPointCut()")
  31. public Object around(ProceedingJoinPoint point) throws Throwable {
  32. DataSource dataSource = getDataSource(point);
  33. if (StringUtils.isNotNull(dataSource)) {
  34. DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
  35. }
  36. try {
  37. return point.proceed();
  38. } finally {
  39. // 销毁数据源 在执行方法之后
  40. DynamicDataSourceContextHolder.clearDataSourceType();
  41. }
  42. }
  43. /**
  44. * 获取需要切换的数据源
  45. */
  46. public DataSource getDataSource(ProceedingJoinPoint point) {
  47. MethodSignature signature = (MethodSignature) point.getSignature();
  48. DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
  49. if (Objects.nonNull(dataSource)) {
  50. return dataSource;
  51. }
  52. return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
  53. }
  54. }