JdbcTemplateAdvice.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.yihu.hos.interceptor;
  2. import com.yihu.hos.common.constants.ContextAttributes;
  3. import org.apache.commons.lang3.StringUtils;
  4. import org.aspectj.lang.ProceedingJoinPoint;
  5. import org.aspectj.lang.annotation.Around;
  6. import org.aspectj.lang.annotation.Aspect;
  7. import org.springframework.stereotype.Component;
  8. /**
  9. * jdbc
  10. * @author HZY
  11. * @vsrsion 1.0
  12. * Created at 2016/12/7.
  13. */
  14. @Aspect
  15. @Component
  16. public class JdbcTemplateAdvice {
  17. @Around("execution(* org.springframework.jdbc.core.JdbcTemplate.query*(..)) || execution(* org.springframework.jdbc.core.JdbcTemplate.execute*(..))")
  18. public Object process(ProceedingJoinPoint point) throws Throwable {
  19. String schemaName = getSchema();
  20. //访问目标方法的参数:
  21. Object[] args = point.getArgs();
  22. if (args != null && args.length > 0 && args[0].getClass() == String.class) {
  23. String completeSql = args[0].toString();
  24. if (StringUtils.isNotEmpty(schemaName)) {
  25. String myCatAnnotation = "/*#mycat:schema=" + schemaName + "*/ ";
  26. completeSql = myCatAnnotation + completeSql;
  27. }
  28. args[0]=completeSql;
  29. }
  30. //用改变后的参数执行目标方法
  31. Object returnValue = point.proceed(args);
  32. return returnValue;
  33. }
  34. // @Before("execution(* org.springframework.jdbc.core.JdbcTemplate.query*(..)) || execution(* org.springframework.jdbc.core.JdbcTemplate.execute*(..))")
  35. // public void permissionCheck(JoinPoint point) {
  36. // System.out.println("@Before:模拟权限检查...");
  37. // System.out.println("@Before:目标方法为:" +
  38. // point.getSignature().getDeclaringTypeName() +
  39. // "." + point.getSignature().getName());
  40. // System.out.println("@Before:参数为:" + Arrays.toString(point.getArgs()));
  41. // System.out.println("@Before:被织入的目标对象为:" + point.getTarget());
  42. //
  43. // String schemaName = getSchema();
  44. // //访问目标方法的参数:
  45. // Object[] args = point.getArgs();
  46. // if (args != null && args.length > 0 && args[0].getClass() == String.class) {
  47. // String completeSql = args[0].toString();
  48. // if (StringUtils.isNotEmpty(schemaName)) {
  49. // String myCatAnnotation = "/*#mycat:schema=" + schemaName + "*/ ";
  50. // completeSql = myCatAnnotation + completeSql;
  51. // }
  52. // args[0]=completeSql;
  53. // }
  54. //
  55. // }
  56. private String getSchema() {
  57. return LocalContext.getContext().getAttachment(ContextAttributes.SCHEMA);
  58. }
  59. }