DataSourceAspect.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.sqx.datasource.aspect;
  2. import com.sqx.datasource.annotation.DataSource;
  3. import com.sqx.datasource.config.DynamicContextHolder;
  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. @Aspect
  19. @Component
  20. @Order(Ordered.HIGHEST_PRECEDENCE)
  21. public class DataSourceAspect {
  22. protected Logger logger = LoggerFactory.getLogger(getClass());
  23. @Pointcut("@annotation(com.sqx.datasource.annotation.DataSource) " +
  24. "|| @within(com.sqx.datasource.annotation.DataSource)")
  25. public void dataSourcePointCut() {
  26. }
  27. @Around("dataSourcePointCut()")
  28. public Object around(ProceedingJoinPoint point) throws Throwable {
  29. MethodSignature signature = (MethodSignature) point.getSignature();
  30. Class targetClass = point.getTarget().getClass();
  31. Method method = signature.getMethod();
  32. DataSource targetDataSource = (DataSource)targetClass.getAnnotation(DataSource.class);
  33. DataSource methodDataSource = method.getAnnotation(DataSource.class);
  34. if(targetDataSource != null || methodDataSource != null){
  35. String value;
  36. if(methodDataSource != null){
  37. value = methodDataSource.value();
  38. }else {
  39. value = targetDataSource.value();
  40. }
  41. DynamicContextHolder.push(value);
  42. logger.debug("set datasource is {}", value);
  43. }
  44. try {
  45. return point.proceed();
  46. } finally {
  47. DynamicContextHolder.poll();
  48. logger.debug("clean datasource");
  49. }
  50. }
  51. }