@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;
}
}