@Component @Aspect @Conditional(NoUnitTestCondition.class) public class AopAudit { @Autowired private ApplicationContext context; // 單元測試的profile環境標識 @Value("${unit.test.active.profile:utest}") private String activeProfile; @Around(value = "@annotation(com.conf.mybatis.ReplaceTableRule)") public Object boBefore1(ProceedingJoinPoint joinPoint) { String res = "----- [+]環繞前置通知 targetObject:" + joinPoint.getTarget() +" joinPoint:" + joinPoint; Signature signature = joinPoint.getSignature(); MethodSignature sign = (MethodSignature) joinPoint.getSignature(); Method method = sign.getMethod(); ReplaceTableRule annotation = null; //獲取aop截取方法上的註解 annotation = method.getAnnotation(ReplaceTableRule.class); if (annotation != null) { // 獲取代理處理器 InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation); // 過去私有 memberValues 屬性 try{ Field f = invocationHandler.getClass().getDeclaredField("memberValues"); // 由於這個字段事 private final 修飾,因此要打開權限 f.setAccessible(true); // 獲取實例的屬性map Map<String, Object> memberValues = (Map<String, Object>) f.get(invocationHandler); // 修改屬性值 memberValues.put("tableType", "2qq"); memberValues.put("table", "2qq"); System.out.println(); }catch (NoSuchFieldException e){ }catch (Exception ie){ } } Object result = null; try { //執行目標方法 result = joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } String ret = "----- [+]環繞後置通知 targetObject:" + joinPoint.getTarget() +" kind:" + joinPoint.getKind(); System.out.println(ret); String methodName = joinPoint.getSignature().getName(); System.out.println("Method Name : [" + methodName + "] ---> AOP before "); System.out.println("被代理的對象:" + joinPoint.getTarget()); System.out.println("代理對象本身:" + joinPoint.getThis()); return result; } /** * 是否單元測試 * @return */ public boolean disparkTest() { String[] profiles = context.getEnvironment().getActiveProfiles(); if (profiles == null || profiles.length == 0) { return false; } String profile = profiles[0]; if (activeProfile.equals(profile)) { return true; } return false; } }