@Around("readDao()") public Object aroundTemplateRead(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{ ReadWriteSplittingDataSourceHolder.setReadDataSource(); Object processResult = null; //需要先定位是哪个DataSourceGroupId的 //设置为读状态 processResult = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs()); return processResult; }
@Around("execution(@org.apache.servicecomb.tracing.Span * *(..)) && @annotation(spanAnnotation)") public Object advise(ProceedingJoinPoint joinPoint, Span spanAnnotation) throws Throwable { String spanName = spanAnnotation.spanName(); String callPath = spanAnnotation.callPath(); Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); LOG.debug("Generating zipkin span for method {}", method.toString()); if ("".equals(spanName)) { spanName = method.getName(); } if ("".equals(callPath)) { callPath = method.toString(); } return adviser.invoke(spanName, callPath, joinPoint::proceed); }
@Around("methodAnnotated() || constructorAnnotated()")//在连接点进行方法替换 public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); LogUtils.showLog("TimeLog getDeclaringClass", methodSignature.getMethod().getDeclaringClass().getCanonicalName()); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); long startTime = System.nanoTime(); Object result = joinPoint.proceed();//执行原方法 StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(methodName + ":"); for (Object obj : joinPoint.getArgs()) { if (obj instanceof String) keyBuilder.append((String) obj); else if (obj instanceof Class) keyBuilder.append(((Class) obj).getSimpleName()); } String key = keyBuilder.toString(); LogUtils.showLog("TimeLog", (className + "." + key + joinPoint.getArgs().toString() + " --->:" + "[" + (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) + "ms]"));// 打印时间差 return result; }
@Around("methodAnnotated()")//在连接点进行方法替换 public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String methodName = methodSignature.getName(); MemoryCacheManager mMemoryCacheManager = MemoryCacheManager.getInstance(); StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(methodName); for (Object obj : joinPoint.getArgs()) { if (obj instanceof String) keyBuilder.append((String) obj); else if (obj instanceof Class) keyBuilder.append(((Class) obj).getSimpleName()); } String key = keyBuilder.toString(); Object result = mMemoryCacheManager.get(key);//key规则 : 方法名+参数1+参数2+... LogUtils.showLog("MemoryCache", "key:" + key + "--->" + (result != null ? "not null" : "null")); if (result != null) return result;//缓存已有,直接返回 result = joinPoint.proceed();//执行原方法 if (result instanceof List && result != null && ((List) result).size() > 0 //列表不为空 || result instanceof String && !TextUtils.isEmpty((String) result)//字符不为空 || result instanceof Object && result != null)//对象不为空 mMemoryCacheManager.add(key, result);//存入缓存 LogUtils.showLog("MemoryCache", "key:" + key + "--->" + "save"); return result; }
/** * @param pjp the proceeding join point * @return the result of the method being wrapped * @throws Throwable */ @Around("springRepositories()") public Object traceAroundRepositoryMethods(ProceedingJoinPoint pjp) throws Throwable { logger.trace("Advising repository"); boolean hasClassAnnotation = false; for (Class<?> i : pjp.getTarget().getClass().getInterfaces()) { if (i.getAnnotation(XRayEnabled.class) != null) { hasClassAnnotation = true; break; } } if (hasClassAnnotation) { return this.processXRayTrace(pjp); } else { return XRayInterceptorUtils.conditionalProceed(pjp); } }
/** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("loggingPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } }
@Around("anyRepositoryMethod()") public Object invokeWithCatTransaction(ProceedingJoinPoint joinPoint) throws Throwable { String name = joinPoint.getSignature().getDeclaringType().getSimpleName() + "." + joinPoint.getSignature() .getName(); Transaction catTransaction = Tracer.newTransaction("SQL", name); try { Object result = joinPoint.proceed(); catTransaction.setStatus(Transaction.SUCCESS); return result; } catch (Throwable ex) { catTransaction.setStatus(ex); throw ex; } finally { catTransaction.complete(); } }
@Around("execution(* org.packt.aop.transaction.dao.impl.EmployeeDaoImpl.getEmployees(..))") public Object cacheMonitor(ProceedingJoinPoint joinPoint) throws Throwable { logger.info("executing " + joinPoint.getSignature().getName()); Cache cache = cacheManager.getCache("employeesCache"); logger.info("cache detected is " + cache.getName()); logger.info("begin caching....."); String key = joinPoint.getSignature().getName(); logger.info(key); if(cache.get(key) == null){ logger.info("caching new Object....."); Object result = joinPoint.proceed(); cache.put(new Element(key, result)); return result; }else{ logger.info("getting cached Object....."); return cache.get(key).getObjectValue(); } }
@Around("classPointcut() && delPointcut() && @annotation(mapping)") public String delEmployee(ProceedingJoinPoint joinPoint, RequestMapping mapping) throws Throwable{ HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); logger.info("executing " + joinPoint.getSignature().getName()); int userId = (Integer)req.getSession().getAttribute("userId"); System.out.println("userId" + userId); List<RolePermission> permission = loginServiceImpl.getPermissionSets(userId); if(isAuthroize(permission)){ logger.info("user " + userId + " is authroied to delete"); joinPoint.proceed(); return "menu"; }else{ logger.info("user " + userId + " is NOT authroied to delete"); return "banned"; } }
/** * 接收到客户端请求时执行 * * @param pjp * @return * @throws Throwable */ @Around("controllerAspect()") public Object execute(ProceedingJoinPoint pjp) throws Throwable { // 从切点上获取目标方法 MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); /** * 验证Token */ if (method.isAnnotationPresent(Token.class)) { // 从 request header 中获取当前 token HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String token = request.getHeader(DEFAULT_TOKEN_NAME); if (StringUtils.isEmpty(token)) { throw new TokenException("客户端X-Token参数不能为空,且从Header中传入,如果没有登录,请先登录获取Token"); } // 检查 token 有效性 if (!tokenManager.checkToken(token)) { String message = String.format("Token [%s] 非法", token); throw new TokenException(message); } } // 调用目标方法 return pjp.proceed(); }
@Around("retryOnOptFailure()") public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable { int numAttempts = 0; do { numAttempts++; try { return pjp.proceed(); } catch (OptimisticLockingFailureException ex) { if (numAttempts > maxRetries) { //log failure information, and throw exception throw ex; } else { //log failure information for audit/reference //will try recovery } } } while (numAttempts <= this.maxRetries); return null; }
/** * Aspect for logging before service calls. * * @param joinPoint joinPoint * @return method result * @throws Throwable throwable */ @SneakyThrows @Around("servicePointcut() && !excluded()") public Object logBeforeService(ProceedingJoinPoint joinPoint) { StopWatch stopWatch = StopWatch.createStarted(); try { logStart(joinPoint); Object result = joinPoint.proceed(); logStop(joinPoint, result, stopWatch); return result; } catch (Exception e) { logError(joinPoint, e, stopWatch); throw e; } }
@Around("@annotation(ReadOnlyDataAccess)") public Object accessDataReadOnly(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String dataConsistency = request.getHeader(HEADER_DATA_CONSISTENCY); Object returnValue; if (isQueryStandByEnabled && "weak".equals(dataConsistency)) { if (logger.isDebugEnabled()) { logger.debug("marking " + joinPoint.getSignature().getName() + " read only "); } DataTypeHolder.setReadOnlyData(); try { returnValue = joinPoint.proceed(); } catch (Throwable throwable) { DataTypeHolder.clear(); logger.info("retrying the request " + joinPoint.getSignature().getName() + " in primary"); returnValue = joinPoint.proceed(); } finally { DataTypeHolder.clear(); } return returnValue; } return joinPoint.proceed(); }
@Around("dataSourcePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); DataSource ds = method.getAnnotation(DataSource.class); if (ds == null) { DynamicDataSource.setDataSource(DataSourceNames.FIRST); log.debug("set datasource is " + DataSourceNames.FIRST); } else { DynamicDataSource.setDataSource(ds.name()); log.debug("set datasource is " + ds.name()); } try { return point.proceed(); } finally { DynamicDataSource.clearDataSource(); log.debug("clean datasource"); } }
@Around("execution(java.lang.String org.hibernate.sql.*.toStatementString(..))") public String toStatementStringAround(ProceedingJoinPoint joinPoint) throws Throwable { Dialect dialect = getDialect(joinPoint.getTarget()); if (!(dialect instanceof PhoenixDialect)) { // Nothing to deal with return (String) joinPoint.proceed(); } String statement = (String) joinPoint.proceed(); if (joinPoint.getTarget() instanceof Insert || joinPoint.getTarget() instanceof InsertSelect) { return statement.replaceFirst("insert into", "upsert into"); } else if (joinPoint.getTarget() instanceof Update) { return createUpsertValues((Update) joinPoint.getTarget()); } return statement; }
@Around("execution( * com.way.learning.service..*ServiceImpl.checkAnswer(..))") public Object updateAnswerResult(ProceedingJoinPoint pjp) throws Throwable{ System.out.println(pjp.getSignature().getName()+"() target method call...."); Member mvo=(Member)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Object[ ] params=pjp.getArgs(); int questionNo=Integer.parseInt(params[0].toString()); String userId=mvo.getUserId(); answerService.updatePostCntSubmit(questionNo); answerService.updateMyCntSubmit(questionNo,userId ); Object result= pjp.proceed(); if(result.toString().equals("1") ){ answerService.updatePostCntRight(questionNo); answerService.updateMyCntRight(questionNo,userId ); }else answerService.updateMyCntWrong(questionNo, userId ); return result; }
@Around("execution( * com.way.learning.service..*ServiceImpl.insertBoard(..))" +" or execution( * com.way.learning.service..*ServiceImpl.insertReply(..))" +" or execution( * com.way.learning.service..*ServiceImpl.insertLecture(..))" ) public Object updateInsertActivity(ProceedingJoinPoint pjp) throws Throwable{ Object result= pjp.proceed(); System.out.println(pjp.getSignature().getName()+"() target method call...."); System.out.println("activity aop result:"+result); Member mvo=(Member)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(result.toString().equals("1")){ activityService.updateActivity(mvo.getUserId(),pjp.getSignature().getName()); } return result; }
/** * Advice that logs when a method is entered and exited. * * @param joinPoint join point for advice * @return result * @throws Throwable throws IllegalArgumentException */ @Around("applicationPackagePointcut() && springBeanPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } }
@Around( "execution(org.springframework.http.ResponseEntity com.aidijing.*.controller.*Controller.*(..)) )" ) public Object returnValueHandle ( ProceedingJoinPoint joinPoint ) throws Throwable { Object returnValue = joinPoint.proceed(); ResponseEntity responseEntity = ( ResponseEntity ) returnValue; // 用户权限或者用户自定义处理 final RolePermissionResource currentRequestRolePermissionResource = ContextUtils.getCurrentRequestRolePermissionResource(); if ( Objects.isNull( currentRequestRolePermissionResource ) ) { return returnValue; } if ( ResponseEntityPro.WILDCARD_ALL.equals( currentRequestRolePermissionResource.getResourceApiUriShowFields() ) ) { ContextUtils.removeCurrentRequestRolePermissionResource(); return returnValue; } final String resourceApiUriShowFields = currentRequestRolePermissionResource.getResourceApiUriShowFields(); final String filterAfterJsonBody = toFilterJson( responseEntity.getBody() , resourceApiUriShowFields ); final Object filterAfterBody = jsonToType( filterAfterJsonBody , responseEntity.getBody().getClass() ); ContextUtils.removeCurrentRequestRolePermissionResource(); return new ResponseEntity<>( filterAfterBody , responseEntity.getHeaders() , responseEntity.getStatusCode() ); }
@Around("selectAdd()") public int aroundAdvise(ProceedingJoinPoint joinPoint) { long start_time=System.currentTimeMillis(); logger.info("around advise before "+joinPoint.getSignature() +" B.L.method getting invoked"); Integer o=null; try { o=(Integer)joinPoint.proceed(); logger.info("number of rows affected:-"+o); } catch (Throwable e) { // TODO Auto-generated catch block e.printStackTrace(); } logger.info("around advise after "+joinPoint.getSignature()+ " B.L.method getting invoked"); long end_time=System.currentTimeMillis(); logger.info(joinPoint.getSignature()+" took " + (end_time-start_time)+" to complete"); return o.intValue(); }
@Around("methodAnnotated()") public Object aroundJoinPoint(final ProceedingJoinPoint joinPoint) throws Throwable { final Object[] result = {null}; if (Looper.myLooper() == Looper.getMainLooper()) { result[0] = joinPoint.proceed(); } else { C.doMain(new Runnable() { @Override public void run() { try { result[0] = joinPoint.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } } }); } return result; }
/** * 拦截HttpClient的Post与Get方法. * */ @Around("execution(* org.apache.http.client.HttpClient.execute(..)) && args(httpUriRequest)") public Object around(final ProceedingJoinPoint proceedingJoinPoint, final HttpUriRequest httpUriRequest) throws Throwable { final long startTime = System.currentTimeMillis(); final Object[] args = proceedingJoinPoint.getArgs(); final Object result = proceedingJoinPoint.proceed(args); if (httpUriRequest instanceof HttpUriRequest) { final String methodName = httpUriRequest.getMethod(); final String className = httpUriRequest.getURI().toString(); Tracer.getInstance().addBinaryAnnotation(className, methodName, (int) (System.currentTimeMillis() - startTime)); } return result; }
@Around("methodAnnotatedWithTrace() || constructorAnnotatedTrace()") public Object traceMethod(final ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Trace trace = methodSignature.getMethod().getAnnotation(Trace.class); if (trace!=null && !trace.enable()) { return joinPoint.proceed(); } String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); Object result = joinPoint.proceed(); stopWatch.stop(); if (Preconditions.isBlank(className)) { className = "Anonymous class"; } L.i(className, buildLogMessage(methodName, stopWatch.getElapsedTime())); return result; }
/** * 查询物品最低价时统计物品查询 * @param point 切点 * @return 切面方法返回值 * @throws Throwable 异常 */ @Around("execution(public * com.bnade.wow.controller.CheapestAuctionController.findAll(..))") public Object process(ProceedingJoinPoint point) throws Throwable { // 获取方法参数 CheapestAuction cheapestAuction = null; Object[] args = point.getArgs(); if (args != null && args.length == 1) { cheapestAuction = (CheapestAuction)args[0]; } // 实际方法运行 Object returnValue = point.proceed(); if (cheapestAuction != null && returnValue != null && returnValue instanceof List) { // 当有返回数据时才统计 if (((List) returnValue).size() > 0) { // 获取httprequest ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String ip = IPUtils.getIp(request); // 统计物品搜索 logger.debug("记录ip: {}, item: {}", ip, cheapestAuction.getItemId()); statisticService.recordItemSearchedByIp(ip, "" + cheapestAuction.getItemId()); } } return returnValue; }
/** * Advice that logs when a method is entered and exited. */ @Around("loggingPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName()); throw e; } }
@Around(value = "@annotation(com.reger.datasource.annotation.DataSourceChange)", argNames = "point") public Object doAround(final ProceedingJoinPoint point) throws Throwable { MethodSignature ms = (MethodSignature) point.getSignature(); Method method = ms.getMethod(); Class<?> targetClass = point.getTarget().getClass(); Method targetMethod = targetClass.getMethod(method.getName(), method.getParameterTypes()); DataSourceChange annotation = AnnotationUtils.findAnnotation(targetMethod, DataSourceChange.class); if (annotation == null) return point.proceed(); SwitchExecute<Object> execute= new SwitchExecute<Object>() { @Override public Object run() throws Throwable { return point.proceed(); } }; if (annotation.slave()) { logger.debug("注解到从库执行"); return Proxy.slave(execute); } else { logger.debug("注解到主库执行"); return Proxy.master(execute); } }
@Around("@annotation(com.asura.framework.conf.subscribe.AsuraSubField)") public Object findValue(ProceedingJoinPoint pjp) throws Throwable { Method method = getMethod(pjp); // 获取被拦截方法对象 AsuraSubField asuraSubField = method.getAnnotation(AsuraSubField.class); String key = asuraSubField.appName() + "." + asuraSubField.type() + "." + asuraSubField.code(); String str= DynamicPropertyFactory.getInstance().getStringProperty(key, null).get(); if(Check.NuNStrStrict(str)){ str=ConfigSubscriber.getInstance().getConfigValue(key); if(!Check.NuNStrStrict(str)){ ConfigSubscriber.getInstance().registConfig(key, asuraSubField.defaultValue()); } } if(Check.NuNStrStrict(str)){ str=asuraSubField.defaultValue(); } return str; }
@Around("pointcut()") public void around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("@Around"); // MethodSignature signature = (MethodSignature) joinPoint.getSignature(); // String name = signature.getName(); // 方法名:test // Method method = signature.getMethod(); // 方法:public void com.lqr.androidaopdemo.MainActivity.test(android.view.View) // Class returnType = signature.getReturnType(); // 返回值类型:void // Class declaringType = signature.getDeclaringType(); // 方法所在类名:MainActivity // String[] parameterNames = signature.getParameterNames(); // 参数名:view // Class[] parameterTypes = signature.getParameterTypes(); // 参数类型:View // TestAnnoTrace annotation = method.getAnnotation(TestAnnoTrace.class); // String value = annotation.value(); // int type = annotation.type(); // long beginTime = SystemClock.currentThreadTimeMillis(); joinPoint.proceed(); // long endTime = SystemClock.currentThreadTimeMillis(); // long dx = endTime - beginTime; // System.out.println("耗时:" + dx + "ms"); }
@Around(value = "mQAdminMethodPointCut() || multiMQAdminMethodPointCut()") public Object aroundMQAdminMethod(ProceedingJoinPoint joinPoint) throws Throwable { Object obj = null; try { MQAdminInstance.initMQAdminInstance(); obj = joinPoint.proceed(); } finally { MQAdminInstance.destroyMQAdminInstance(); } return obj; }
@Around("execution (public * com.coderjerry.eds.consumer.mybatis.mapper..*Mapper.*(..))") public Object logCache(ProceedingJoinPoint jp) throws Throwable { Object result = null; String callMethod = jp.getSignature().getDeclaringType().getSimpleName() + "." + jp.getSignature().getName(); long start = System.currentTimeMillis(); try { result = jp.proceed(); logger.debug("SQL execute {} ,cost {}ms", callMethod, (System.currentTimeMillis() - start)); return result; } catch (Throwable e) { logger.error("SQL execute error {} {}",callMethod, e); throw e; } }
@Around("methods() || constructors()") public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); Assertions.assertWorkerThread(); return joinPoint.proceed(); }
@Around("onSaveInstanceState()") public Object onSaveInstanceStateProcess(ProceedingJoinPoint joinPoint) throws Throwable { Object result = joinPoint.proceed(); Object puppet = joinPoint.getTarget(); //Only inject the class that marked by Puppet annotation. Object[] args = joinPoint.getArgs(); Method onSaveInstanceState = getRiggerMethod("onSaveInstanceState", Object.class, Bundle.class); onSaveInstanceState.invoke(getRiggerInstance(), puppet, args[0]); return result; }
@Around("execution(@com.app.annotation.aspect.Permission * *(..)) && @annotation(permission)") public void aroundJoinPoint(ProceedingJoinPoint joinPoint, Permission permission) throws Throwable { AppCompatActivity ac = (AppCompatActivity) App.getAppContext().getCurActivity(); new AlertDialog.Builder(ac) .setTitle("提示") .setMessage("为了应用可以正常使用,请您点击确认申请权限。") .setNegativeButton("取消", null) .setPositiveButton("允许", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MPermissionUtils.requestPermissionsResult(ac, 1, permission.value() , new MPermissionUtils.OnPermissionListener() { @Override public void onPermissionGranted() { try { joinPoint.proceed();//获得权限,执行原方法 } catch (Throwable e) { e.printStackTrace(); } } @Override public void onPermissionDenied() { MPermissionUtils.showTipsDialog(ac); } }); } }) .create() .show(); }
@Around("construct()") public Object constructProcess(ProceedingJoinPoint joinPoint) throws Throwable { Object result = joinPoint.proceed(); Object puppet = joinPoint.getTarget(); //Only inject the class that marked by Puppet annotation. Method onAttach = getRiggerMethod("onPuppetConstructor", Object.class); onAttach.invoke(getRiggerInstance(), puppet); return result; }
@Around("pointCutMethod()") public Object around(ProceedingJoinPoint pjp) throws Throwable { HttpServletRequest req = (HttpServletRequest) pjp.getArgs()[0]; // IP valid String ip = getClientIP(req); if (validIP(ip)) { return pjp.proceed(); } else { logger.error("Warning : under attack from {}", ip); return "403 Forbidden! Your ip is " + ip; } }
@Around("@annotation(com.springtest.aopannotation.DataSource)") public Object handleAnnotation(ProceedingJoinPoint pjp) throws Throwable { Class<? extends Object> invokeClass = pjp.getTarget().getClass(); String signatureName = pjp.getSignature().getName(); Method methods[] = invokeClass.getMethods(); for (Method method : methods) { if (method.getName().equals(signatureName)) { String paramCollection = method.getAnnotation(DataSource.class).name(); System.out.println("finished switching datasource to "+paramCollection); } } return pjp.proceed(); }
@Around("pointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("******"); System.out.println("logAround() is running!"); System.out.println("hijacked method : " + joinPoint.getSignature().getName()); System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs())); System.out.println("Around before is running!"); Object retVal = joinPoint.proceed(); System.out.println("Around after is running!"); System.out.println("******"); return retVal; }