
在Spring Boot开发中,我们经常遇到需要在多个方法或类中执行相似的、非核心业务逻辑(例如日志记录、权限校验、性能监控或数据预处理)。如果将这些逻辑直接嵌入到每个业务方法中,会导致代码冗余、可读性差,并且难以维护。用户提出的需求正是希望通过一个自定义注解,来标记需要这些额外逻辑的方法或类,而无需手动修改这些方法的内部实现。这种需求可以通过Spring的AOP(Aspect-Oriented Programming,面向切面编程)机制结合自定义注解来优雅地解决。
2. Spring AOP核心概念概述Spring AOP是Spring框架的核心模块之一,它允许开发者定义横切关注点(Cross-cutting Concerns),并将这些关注点模块化为独立的切面(Aspect)。AOP的核心概念包括:
- 切面(Aspect):一个模块化的横切关注点,通常是一个类,包含了通知和切点。
- 连接点(Join Point):程序执行过程中可以插入切面的点,例如方法调用、方法执行、字段设置等。在Spring AOP中,通常指方法的执行。
- 通知(Advice):切面在特定连接点执行的动作,例如@Before(前置通知)、@AfterReturning(后置通知,方法正常返回后)、@AfterThrowing(异常通知,方法抛出异常后)、@After(最终通知,无论如何都会执行)和@Around(环绕通知)。
- 切点(Pointcut):一个表达式,用于定义哪些连接点应该被通知。
- 目标对象(Target Object):被一个或多个切面通知的对象。
- 织入(Weaving):将切面应用到目标对象并创建新的代理对象的过程。
为了实现通过自定义注解添加逻辑,我们将主要使用自定义注解来定义切点,并使用环绕通知(@Around)来包裹目标方法的执行,从而在方法执行前后注入自定义逻辑。
3. 实现步骤详解 3.1 步骤一:定义自定义注解首先,我们需要创建一个自定义注解,用作我们逻辑增强的标记。
package com.example.demo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解,用于标记需要额外逻辑处理的方法或类。
*/
@Target({ElementType.METHOD, ElementType.TYPE}) // 允许注解在方法和类上
@Retention(RetentionPolicy.RUNTIME) // 运行时保留注解信息,以便AOP可以通过反射读取
public @interface MyCustomAnnotation {
String value() default "defaultLogic"; // 可以添加一个可选参数,用于区分不同的逻辑类型
} - @Target: 指定注解可以应用的目标元素类型,这里设置为方法 (ElementType.METHOD) 和类 (ElementType.TYPE)。
- @Retention: 指定注解的保留策略,RetentionPolicy.RUNTIME表示注解信息在运行时依然可用,这是Spring AOP能够通过反射读取注解的关键。
接下来,创建一个Spring组件,并使用@Aspect注解将其声明为一个切面。在这个切面中,我们将定义切点和通知。
package com.example.demo.aspect;
import com.example.demo.annotation.MyCustomAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model; // 导入Model类以处理用户需求
import java.lang.reflect.Method;
import org.aspectj.lang.reflect.MethodSignature;
/**
* 负责处理MyCustomAnnotation注解的切面。
* 在目标方法执行前后注入自定义逻辑。
*/
@Aspect
@Component // 声明为Spring组件,使其能够被Spring容器管理
public class CustomAnnotationAspect {
// 定义一个切点,匹配所有带有@MyCustomAnnotation注解的方法
@Pointcut("@annotation(com.example.demo.annotation.MyCustomAnnotation)")
public void annotatedMethodPointcut() {}
// 定义一个切点,匹配所有类上带有@MyCustomAnnotation注解的类中的方法
@Pointcut("@within(com.example.demo.annotation.MyCustomAnnotation)")
public void annotatedClassPointcut() {}
/**
* 环绕通知,在匹配的连接点执行。
* 允许在目标方法执行前后添加逻辑,并控制目标方法的执行。
*
* @param joinPoint 连接点对象,提供了访问目标方法和参数的能力
* @return 目标方法的返回值
* @throws Throwable 目标方法或通知中抛出的异常
*/
@Around("annotatedMethodPointcut() || annotatedClassPointcut()")
public Object applyCustomLogic(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("--- 进入 CustomAnnotationAspect ---");
// 1. 获取注解信息 (可选,如果需要根据注解参数执行不同逻辑)
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
MyCustomAnnotation annotation = method.getAnnotation(MyCustomAnnotation.class);
if (annotation == null) { // 如果方法上没有,则尝试从类上获取
annotation = joinPoint.getTarget().getClass().getAnnotation(MyCustomAnnotation.class);
}
String logicType = (annotation != null) ? annotation.value() : "unknown";
System.out.println("检测到自定义注解,逻辑类型: " + logicType);
// 2. 在目标方法执行前的逻辑
System.out.println("在方法执行前注入逻辑: " + joinPoint.getSignature().toShortString());
// 示例:根据用户需求,检查方法参数中是否存在Model对象,并向其添加属性
Object[] args = joinPoint.getArgs();
for (Object arg : args) {
if (arg instanceof Model) {
Model model = (Model) arg;
model.addAttribute("keyFromAspect", "valueInjectedByCustomAnnotation");
System.out.println("已向Model注入属性: keyFromAspect='valueInjectedByCustomAnnotation'");
break; // 假设只有一个Model参数
}
}
// 3. 执行目标方法
Object result = joinPoint.proceed(); // 调用目标方法
// 4. 在目标方法执行后的逻辑
System.out.println("在方法执行后注入逻辑: " + joinPoint.getSignature().toShortString());
System.out.println("--- 退出 CustomAnnotationAspect ---");
return result; // 返回目标方法的执行结果
}
} - @Aspect: 标记这是一个切面类。
- @Component: 确保Spring能够扫描并管理这个切面。
- @Pointcut: 定义切点表达式。
- @annotation(com.example.demo.annotation.MyCustomAnnotation):匹配所有直接在方法上带有@MyCustomAnnotation注解的连接点。
- @within(com.example.demo.annotation.MyCustomAnnotation):匹配所有类上带有@MyCustomAnnotation注解的类中的所有方法。通过||运算符可以将这两个切点组合起来,实现类级别和方法级别的注解支持。
- @Around: 环绕通知。它接收一个ProceedingJoinPoint参数,该参数允许我们:
- joinPoint.proceed():执行目标方法。
- joinPoint.getArgs():获取目标方法的参数。
- joinPoint.getSignature():获取目标方法的签名信息。
- joinPoint.getTarget():获取目标对象实例。
- 通过反射获取注解实例,可以读取注解的参数(如value)。
现在,我们可以在Spring Controller或其他组件的方法或类上使用@MyCustomAnnotation了。
Teleporthq
一体化AI网站生成器,能够快速设计和部署静态网站
182
查看详情
package com.example.demo.controller;
import com.example.demo.annotation.MyCustomAnnotation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 示例控制器,演示自定义注解的应用。
*/
@Controller
@MyCustomAnnotation("controllerLevelLogic") // 将注解应用到类级别,该类所有方法都将受AOP影响
public class ExController {
@GetMapping("/index")
public String index(Model model){
System.out.println("ExController: 原始 index 方法执行。");
// 此时,Model中已经包含了Aspect注入的 "keyFromAspect" 属性
model.addAttribute("originalData", "This is original data from controller.");
return "index"; // 假设存在一个名为 index.html 的视图
}
@MyCustomAnnotation("methodLevelLogic") // 将注解应用到方法级别,覆盖类级别注解或独立生效
@GetMapping("/another")
public String anotherMethod(Model model){
System.out.println("ExController: 原始 anotherMethod 方法执行。");
// 此时,Model中也包含了Aspect注入的 "keyFromAspect" 属性
model.addAttribute("moreData", "Additional data from another method.");
return "another"; // 假设存在一个名为 another.html 的视图
}
} 3.4 步骤四:配置Spring Boot应用
在Spring Boot项目中,通常只需要添加spring-boot-starter-aop依赖,Spring Boot会自动配置AOP代理。
pom.xml 配置:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version> <!-- 根据实际情况选择版本 -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot AOP Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- 如果使用Thymeleaf或其他模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project> 主应用类:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// import org.springframework.context.annotation.EnableAspectJAutoProxy; // Spring Boot 2.x+ 通常不需要显式添加此注解
@SpringBootApplication
// 如果是旧版本Spring或非Spring Boot项目,可能需要手动开启AOP代理:
// @EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
} 4. 运行与验证
启动Spring Boot应用,然后访问 /index 或 /another 路径。你将在控制台看到如下输出:
--- 进入 CustomAnnotationAspect --- 检测到自定义注解,逻辑类型: controllerLevelLogic (或 methodLevelLogic) 在方法执行前注入逻辑: ExController.index(..) 已向Model注入属性: keyFromAspect='valueInjectedByCustomAnnotation' ExController: 原始 index 方法执行。 在方法执行后注入逻辑: ExController.index(..) --- 退出 CustomAnnotationAspect ---
这表明我们的切面成功地在目标方法执行前后注入了自定义逻辑,包括向Model对象添加属性。在视图层(例如index.html),你可以通过${keyFromAspect}来访问这个由切面注入的属性。
5. 注意事项与最佳实践- 代理机制:Spring AOP默认使用JDK动态代理(针对接口)或CGLIB代理(针对类)。这意味着只有通过Spring容器获取的Bean,其方法调用才会被AOP拦截。对象内部的自调用(this.someMethod())不会被拦截,因为它们不是通过代理对象调用的。如果需要拦截自调用,可以考虑使用AspectJ编译时或加载时织入,或者通过AopContext.currentProxy()获取代理对象。
-
通知类型选择:
- @Before和@After适用于简单的前置/后置操作,不涉及目标方法执行流程的控制。
- @AfterReturning和@AfterThrowing适用于根据方法返回结果或异常进行处理的场景。
- @Around是最强大和灵活的,它完全控制了目标方法的执行,可以决定是否执行目标方法、修改参数、修改
以上就是在Spring Boot中通过自定义注解实现方法逻辑动态增强的详细内容,更多请关注知识资源分享宝库其它相关文章!
相关标签: java html apache app ai win springboot 动态代理 spring框架 spring spring boot html Object 运算符 xml 接口 对象 this 大家都在看: 创建不重复问题的Java测验应用教程 如何在Java中理解异常的概念 安装Java时如何验证javac编译器是否可用 Java中个人博客管理系统实现 创建不重复问题的测验应用:Java 解决方案






发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。