在Spring Boot开发中,我们经常遇到需要在多个方法或类中执行相似的、非核心业务逻辑(例如日志记录、权限校验、性能监控或数据预处理)。如果将这些逻辑直接嵌入到每个业务方法中,会导致代码冗余、可读性差,并且难以维护。用户提出的需求正是希望通过一个自定义注解,来标记需要这些额外逻辑的方法或类,而无需手动修改这些方法的内部实现。这种需求可以通过Spring的AOP(Aspect-Oriented Programming,面向切面编程)机制结合自定义注解来优雅地解决。
Spring AOP是Spring框架的核心模块之一,它允许开发者定义横切关注点(Cross-cutting Concerns),并将这些关注点模块化为独立的切面(Aspect)。AOP的核心概念包括:
为了实现通过自定义注解添加逻辑,我们将主要使用自定义注解来定义切点,并使用环绕通知(@Around)来包裹目标方法的执行,从而在方法执行前后注入自定义逻辑。
首先,我们需要创建一个自定义注解,用作我们逻辑增强的标记。
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"; // 可以添加一个可选参数,用于区分不同的逻辑类型
}接下来,创建一个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; // 返回目标方法的执行结果
}
}现在,我们可以在Spring Controller或其他组件的方法或类上使用@MyCustomAnnotation了。
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 的视图
}
}在Spring Boot项目中,通常只需要添加spring-boot-starter-aop依赖,Spring Boot会自动配置AOP代理。
pom.xml 配置:
4.0.0 org.springframework.boot spring-boot-starter-parent2.7.18 com.example demo0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-aoporg.springframework.boot spring-boot-starter-thymeleaforg.springframework.boot spring-boot-starter-testtest org.springframework.boot spring-boot-maven-plugin
主应用类:
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);
}
}启动Spring
Boot应用,然后访问 /index 或 /another 路径。你将在控制台看到如下输出:
--- 进入 CustomAnnotationAspect --- 检测到自定义注解,逻辑类型: controllerLevelLogic (或 methodLevelLogic) 在方法执行前注入逻辑: ExController.index(..) 已向Model注入属性: keyFromAspect='valueInjectedByCustomAnnotation' ExController: 原始 index 方法执行。 在方法执行后注入逻辑: ExController.index(..) --- 退出 CustomAnnotationAspect ---
这表明我们的切面成功地在目标方法执行前后注入了自定义逻辑,包括向Model对象添加属性。在视图层(例如index.html),你可以通过${keyFromAspect}来访问这个由切面注入的属性。