自定义注解+AOP

自定义注解与AOP(面向切面编程)的结合常常用于在应用程序中划定切面,以便在特定的方法或类上应用横切关注点。以下是一个简单的示例,演示了如何创建自定义注解,并使用Spring AOP来在被注解的方法上应用通知。

如何创建自定义注解

链接

创建注解

首先,创建一个自定义注解:

java 复制代码
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
    String value() default "";
}

这个注解名为 MyCustomAnnotation,它可以标注在方法上,具有一个可选的字符串值。

创建切面

然后,创建一个切面类,定义通知,并使用切入点表达式匹配被 MyCustomAnnotation 注解标注的方法:

java 复制代码
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    @Before("@annotation(myCustomAnnotation)")
    public void beforeAdvice(MyCustomAnnotation myCustomAnnotation) {
        String value = myCustomAnnotation.value();
        System.out.println("Before method execution with custom annotation. Value: " + value);
    }
}

这个切面类使用了 @Before 注解,它的参数是一个切入点表达式 @annotation(myCustomAnnotation),表示在被 MyCustomAnnotation 注解标注的方法执行前执行。方法的参数 MyCustomAnnotation myCustomAnnotation 允许你获取到注解上的值。

最后,在你的服务类中使用 MyCustomAnnotation 注解:

java 复制代码
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @MyCustomAnnotation(value = "Custom Value")
    public void myMethod() {
        System.out.println("Executing myMethod");
    }
}

在这个例子中,MyService 类中的 myMethod 方法上标注了 MyCustomAnnotation 注解。当调用这个方法时,切面中的通知会在方法执行前输出相关信息。

这样,你就通过自定义注解和AOP结合的方式,实现了在特定方法上应用通知的需求。

使用切入点

java 复制代码
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {

    // 定义切入点,匹配所有使用 @MyCustomAnnotation 注解的方法
    @Pointcut("@annotation(com.example.demo.MyCustomAnnotation)")
    public void myCustomAnnotationPointcut() {}

    // 在切入点之前执行通知
    @Before("myCustomAnnotationPointcut()")
    public void beforeAdvice() {
        System.out.println("Before method execution with custom annotation");
    }
}
相关推荐
皮皮林5515 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
卡尔特斯10 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
白鲸开源10 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
ytadpole10 小时前
Java 25 新特性 更简洁、更高效、更现代
java·后端
纪莫10 小时前
A公司一面:类加载的过程是怎么样的? 双亲委派的优点和缺点? 产生fullGC的情况有哪些? spring的动态代理有哪些?区别是什么? 如何排查CPU使用率过高?
java·java面试⑧股
JavaGuide11 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端
用户37215742613511 小时前
Java 轻松批量替换 Word 文档文字内容
java
白鲸开源11 小时前
教你数分钟内创建并运行一个 DolphinScheduler Workflow!
java
薛定谔的算法11 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Java中文社群12 小时前
有点意思!Java8后最有用新特性排行榜!
java·后端·面试