当前位置: 首页 > news >正文

自定义注解+AOP

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

如何创建自定义注解

链接

创建注解

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

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 注解标注的方法:

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 注解:


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结合的方式,实现了在特定方法上应用通知的需求。

使用切入点

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");}
}
http://www.lryc.cn/news/240290.html

相关文章:

  • Ribbon
  • git -1
  • 基于SSM+Vue的鲜花销售系统/网上花店系统
  • 安卓:Android Studio4.0~2023中正确的打开Android Device Monitor
  • 装备制造企业设备远程运维平台的建设-天拓四方分享
  • 群晖NAS搭建WebDav服务做文件共享,可随时随地远程访问
  • c++调用Lua(table嵌套写法)
  • 算法复杂度分析
  • 几款Java源码扫描工具(FindBugs、PMD、SonarQube、Fortify、WebInspect)
  • java springboot测试类鉴定虚拟MVC请求 返回内容与预期值是否相同
  • MongoDB随记
  • 839 - Not so Mobile (UVA)
  • php字符串处理函数的使用
  • UEC++ day8
  • 学习记录——ipv4、ipv6与ip、DNS、网络协议
  • cefsharp119.4.30(cef119.4.3,Chromium119.0.6045.159)版本升级体验支持H264及其他多个H264版本
  • “index“ should always be multi-word
  • 服务器64GB内存、8核CPU的MySQL 8配置参数
  • Python+Qt虹膜检测识别
  • 我的创作纪念日——365天
  • 安卓手机便签APP用哪个,手机上好用的便签APP是什么
  • 前端Date对象的使用锦集
  • 如何将ONLYOFFICE与Python应用程序集成
  • vector的简单模拟实现_C++
  • 合并两个有序链表,剑指offer,力扣
  • Delphi 12 Athens 发布了!
  • 基于Haclon的Blob分析
  • 安卓手机好用的清单软件有哪些?
  • 【追求卓越02】数据结构--链表
  • qt按照不同编码格式读取文字(UTF-16LE,UTF-8,UTF-8BOM,UTF-16BE)