1,定义注解
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Change {
String value() default “1”;
}
2,定义注解切面
@Component
@Aspect
public class AnnotationAspect {
@Pointcut("@annotation(Change)")
public void annotationPointcut() {
}
@Before("annotationPointcut()")
public void beforePointcut(JoinPoint joinPoint) {
System.out.println("before:"+JSON.toString(joinPoint.getArgs()));
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
Change annotation = method.getAnnotation(Change.class);
String value = annotation.value();
System.out.println("准备" + value);
}
@After("annotationPointcut()")
public void afterPointcut(JoinPoint joinPoint) {
System.out.println("after:"+JSON.toString(joinPoint.getArgs()));
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
Change annotation = method.getAnnotation(Change.class);
String value = annotation.value();
System.out.println("结束" + value);
}
}
3,测试
@RestController
public class AnnotationTest{
@GetMapping(“testAno”)
@Change(“改变”)
public String testAno(@RequestParam String msg){
System.out.println(“test…”);
return msg;
}
}
4,结果
before:[“123”]
准备改变
test…
after:[“123”]
结束改变