DataSourceAspect.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.izouma.awesomeadmin.datasource;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.aspectj.lang.annotation.Pointcut;
  6. import org.aspectj.lang.reflect.MethodSignature;
  7. import org.springframework.stereotype.Component;
  8. import java.lang.reflect.Method;
  9. @Component
  10. @Aspect
  11. public class DataSourceAspect {
  12. @Pointcut("execution(public * com.izouma.awesomeadmin.dao..*(..)))")
  13. public void pointcut() {
  14. }
  15. /**
  16. * 拦截目标方法,获取由@DataSource指定的数据源标识,设置到线程存储中以便切换数据源
  17. *
  18. * @param point
  19. * @throws Exception
  20. */
  21. @Before(value = "pointcut()")
  22. public void intercept(JoinPoint point) {
  23. //默认使用默认datasource
  24. DynamicDataSourceHolder.setDataSource("dataSource");
  25. Class<?> target = point.getTarget().getClass();
  26. MethodSignature signature = (MethodSignature) point.getSignature();
  27. // 默认使用目标类型的注解,如果没有则使用其实现接口的注解
  28. for (Class<?> clazz : target.getInterfaces()) {
  29. resolveDataSource(clazz, signature.getMethod());
  30. }
  31. resolveDataSource(target, signature.getMethod());
  32. }
  33. /**
  34. * 提取目标对象方法注解和类型注解中的数据源标识
  35. *
  36. * @param clazz
  37. * @param method
  38. */
  39. private void resolveDataSource(Class<?> clazz, Method method) {
  40. try {
  41. Class<?>[] types = method.getParameterTypes();
  42. // 默认使用类型注解
  43. if (clazz.isAnnotationPresent(DataSource.class)) {
  44. DataSource source = clazz.getAnnotation(DataSource.class);
  45. DynamicDataSourceHolder.setDataSource(source.value());
  46. }
  47. // 方法注解可以覆盖类型注解
  48. Method m = clazz.getMethod(method.getName(), types);
  49. if (m != null && m.isAnnotationPresent(DataSource.class)) {
  50. DataSource source = m.getAnnotation(DataSource.class);
  51. DynamicDataSourceHolder.setDataSource(source.value());
  52. }
  53. } catch (Exception e) {
  54. System.out.println(clazz + ":" + e.getMessage());
  55. }
  56. }
  57. }