markdown Aop简单使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Aop简单使用相关的知识,希望对你有一定的参考价值。

If we want to use aop to record which method is being called

1. build the aop annotation
```
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AopExample {
  String methodName();
}
```
2. put it on your method
```
  @AopExample(methodName = "appendName")
  public String appendName(String param){
    return "param is : "+param;
  }
```

3. intercept method by aop
we build the AopDemo class
```
@Aspect
@Component
public class AopDemo {

  @AfterReturning(
      value =
          "@annotation(com.demo.bean.aop.AopExample))
  public Object recordMethod(JoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    AopExample aop = signature.getMethod().getAnnotation(AopExample.class);
    String theMethod = aop.methodName();
    System.out.println(theMethod);
    return null;
  }
}
```
we got the method appendName now

How to catch the parameter when we invoke appendName?
just appoint the method name on interceopter
```
  @AfterReturning(
      value =
          "@annotation(com.demo.bean.aop.AopExample) && execution(* com.demo.service.AppendService.appendName(..)) && args(param)")
  public Object recordMethod(JoinPoint joinPoint, String param) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    AopExample aop = signature.getMethod().getAnnotation(AopExample.class);
    String theMethod = aop.methodName();
    System.out.println(theMethod);

    System.out.println(param);
    return null;
  }
```
you should notice that this interceptor only intercept the method **appendName** now, so the **recordMethod** only service **appendName** 

and if you want to get return value
```
  @AfterReturning(
      value =
          "@annotation(com.demo.bean.aop.AopExample) && execution(* com.demo.service.AppendService.appendName(..)) && args(param)"
          , returning = "returnValue")
  public Object recordMethod(JoinPoint joinPoint, String param, String returnValue) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    AopExample aop = signature.getMethod().getAnnotation(AopExample.class);
    String theMethod = aop.methodName();
    System.out.println(theMethod);

    System.out.println(param);
    
    System.out.println(returnValue);
    return null;
  }
```

以上是关于markdown Aop简单使用的主要内容,如果未能解决你的问题,请参考以下文章

Autofac的AOP面向切面编程研究

Spring--AOP就这么简单

Spring--AOP就这么简单

spring aop简单应用

简单粗暴:使用AOP帮你记录日志

菜鸟学习Spring——60s配置XML方法实现简单AOP