自定义注解+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");
    }
}
相关推荐
不倒翁玩偶7 分钟前
IDEA导入新的SpringBoot项目没有启动按钮
java·spring boot·intellij-idea
猫头虎8 分钟前
基于信创openEuler系统安装部署OpenTeleDB开源数据库的实战教程
数据库·redis·sql·mysql·开源·nosql·database
爬山算法12 分钟前
MongoDB(1)什么是MongoDB?
数据库·mongodb
Nandeska18 分钟前
17、MySQL InnoDB ReplicaSet
数据库·mysql
AI_567818 分钟前
SQL性能优化全景指南:从量子执行计划到自适应索引的终极实践
数据库·人工智能·学习·adb
小小小米粒22 分钟前
Maven Tools
java
释怀不想释怀28 分钟前
Linux文件上传(rz)和下载(sz)压缩(tar.gz)和解压(zip)
linux·运维·服务器
IOsetting36 分钟前
金山云主机添加开机路由
运维·服务器·开发语言·网络·php
kali-Myon37 分钟前
2025春秋杯网络安全联赛冬季赛-day1
java·sql·安全·web安全·ai·php·web
我是咸鱼不闲呀40 分钟前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划