DataSourceAspect.java 2.1 KB

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