You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.0 KiB

5 months ago
  1. package com.xujie.sys.datasource.aspect;
  2. import com.xujie.sys.datasource.config.DynamicContextHolder;
  3. import com.xujie.sys.datasource.annotation.DataSource;
  4. import org.aspectj.lang.ProceedingJoinPoint;
  5. import org.aspectj.lang.annotation.Around;
  6. import org.aspectj.lang.annotation.Aspect;
  7. import org.aspectj.lang.annotation.Pointcut;
  8. import org.aspectj.lang.reflect.MethodSignature;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.core.Ordered;
  12. import org.springframework.core.annotation.Order;
  13. import org.springframework.stereotype.Component;
  14. import java.lang.reflect.Method;
  15. /**
  16. * 多数据源切面处理类
  17. *
  18. *
  19. */
  20. @Aspect
  21. @Component
  22. @Order(Ordered.HIGHEST_PRECEDENCE)
  23. public class DataSourceAspect {
  24. protected Logger logger = LoggerFactory.getLogger(getClass());
  25. @Pointcut("@annotation(com.xujie.sys.datasource.annotation.DataSource) " +
  26. "|| @within(com.xujie.sys.datasource.annotation.DataSource)")
  27. public void dataSourcePointCut() {
  28. }
  29. @Around("dataSourcePointCut()")
  30. public Object around(ProceedingJoinPoint point) throws Throwable {
  31. MethodSignature signature = (MethodSignature) point.getSignature();
  32. Class targetClass = point.getTarget().getClass();
  33. Method method = signature.getMethod();
  34. DataSource targetDataSource = (DataSource)targetClass.getAnnotation(DataSource.class);
  35. DataSource methodDataSource = method.getAnnotation(DataSource.class);
  36. if(targetDataSource != null || methodDataSource != null){
  37. String value;
  38. if(methodDataSource != null){
  39. value = methodDataSource.value();
  40. }else {
  41. value = targetDataSource.value();
  42. }
  43. DynamicContextHolder.push(value);
  44. logger.debug("set datasource is {}", value);
  45. }
  46. try {
  47. return point.proceed();
  48. } finally {
  49. DynamicContextHolder.poll();
  50. logger.debug("clean datasource");
  51. }
  52. }
  53. }