spring aop中实现变更方法参数以及annotation 博客分类: java 技术 springaopannotationmethodvariable
程序员文章站
2024-02-04 12:10:16
...
- 实现功能:
- 利用spring aop annotation实现切片操作,并改变方法参数的值
- 判断方法或方法的参数上是否有特定的annotation,如果有,则按照其它逻辑进行处理
- aop切片操作
@Component @Aspect public class AopAnnotation { private Logger logger = LoggerFactory.getLogger(getClass()); @Pointcut("execution(public * com.*.*.*(..))") public void pointCut(){ } @Before(value = "pointCut()") public void before(){ logger.info("annotation, before################################"); } @Around("pointCut()") public void around(ProceedingJoinPoint joinPoint){ logger.info("annotation, around################################"); Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); try { joinPoint.proceed(); } catch (Throwable e) { } stopwatch.stop(); logger.info("annotation, ###################cost time: " + joinPoint.getThis().getClass().getName() + "\t" + stopwatch.elapsedMillis() + "(ms)"); } @AfterThrowing(pointcut = "pointCut()") public void aa(){ logger.info("error"); } public Verifier verifier; }
- 声明annotation
-
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Param { String value(); }
- 在joinpoint中进行处理,判断参数是否有annotation
-
@Around("sqlEscapePoint()") public Object sqlEscapeAdvice(ProceedingJoinPoint joinPoint) { logger.info("aroundSqlEscape, around################################"); Object[] objects = joinPoint.getArgs(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Annotation[][] annotations = method.getParameterAnnotations(); for (int i = 0; i < objects.length; i++) { Object tmpObject = objects[i]; boolean notEscape = false; if (annotations.length > 0) { for (Annotation annotation : annotations[i]) { if (annotation.annotationType() == NotEscapeSql.class) { notEscape = true; } } } if (notEscape) { continue; } objects[i] = EscapeUtil.escape(tmpObject, false, false, true); } Stopwatch stopwatch = new Stopwatch(); stopwatch.start(); Object result = null; try { result = joinPoint.proceed(objects); } catch (Throwable e) { logger.error("sql escape", e); } stopwatch.stop(); logger.info("mapper cost time: " + joinPoint.getThis().getClass().getName() + "," + method.getName() + "\t" + stopwatch.elapsedMillis() + "(ms)"); return result; }