@annotation:用于匹配当前执行方法持有指定注解的方法;
新建一个注解类:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLogAnnotation {
String name();
}
新建一个切面类:
@Aspect
@Component
public class CustomAspect {
@Pointcut("@annotation(com.lx.bootaop.MyLogAnnotation)")
public void pointAnnotation() {
}
@Before("pointAnnotation() && @annotation(myLogAnnotation)")
public void annotationBefore(JoinPoint joinPoint, MyLogAnnotation myLogAnnotation) {
System.out.println("AOP拦截==执行before:" + joinPoint.getSignature() + ";name=" + myLogAnnotation.name());
}
}
给需要拦截的方法上增加注解:
@MyLogAnnotation(name = "helloMessAnnotation")
public void helloMessAnnotation() {
System.out.println("helloMessAnnotation");
}
测试验证:

本文介绍了如何使用自定义注解`@MyLogAnnotation`结合Spring AOP实现方法拦截。首先创建了一个名为`MyLogAnnotation`的注解,然后在`CustomAspect`切面类中定义了切点和前置通知,通过`@Before`注解在目标方法执行前打印相关信息。最后,在`helloMessAnnotation`方法上添加了`@MyLogAnnotation`注解进行测试,成功实现了AOP的拦截功能。
1万+

被折叠的 条评论
为什么被折叠?



