
在Spring Boot开发中,我们经常会遇到需要在多个方法中重复执行某些横切关注点(如日志记录、权限校验、事务管理或数据预处理等)的需求。如果将这些逻辑直接嵌入到每个业务方法中,会导致代码冗余、可读性下降,并且难以维护。用户提出的需求是希望通过一个自定义注解来“标记”一个方法或类,然后系统能够自动为这些被标记的方法添加特定的逻辑,例如在Controller方法执行前向Model中添加数据。这种需求非常适合使用Spring AOP来解决。
Spring AOP允许开发者定义横切关注点,并将其从核心业务逻辑中分离出来,通过“切面”的形式在程序运行时动态地织入到目标对象中。结合自定义注解,我们可以精确地指定哪些方法或类应该被这些横切逻辑所增强。
首先,我们需要创建一个自定义注解,用作标记点。这个注解可以没有任何属性,或者包含一些配置属性,以便切面能够根据这些属性进行不同的处理。
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;
/**
* 自定义注解:用于标记需要额外添加Model属性的Controller方法或类
*/
@Target({ElementType.METHOD, ElementType.TYPE}) // 作用于方法和类
@Retention(RetentionPolicy.RUNTIME) // 运行时可见
public @interface AddCustomModelAttr {
/**
* 要添加的Model属性的键
*/
String key() default "defaultKey";
/**
* 要添加的Model属性的值
*/
String value() default "defaultValue";
}注解说明:
接下来,我们将创建一个切面类,其中包含切点(Pointcut)和通知(Advice)。切点定义了哪些方法会被拦截,而通知则包含了要执行的额外逻辑。
package com.example.demo.aspect;
import com.example.demo.annotation.AddCustomModelAttr;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* 自定义Model属性添加切面
*/
@Aspect
@Component
public class CustomModelAttrAspect {
/**
* 定义切点:匹配所有被 @AddCustomModelAttr 注解标记的方法或类
* 注意:这里为了简化示例,我们假设Controller方法会接收Model参数。
* 实际应用中可能需要更复杂的逻辑来获取Model对象。
*/
@Before("@annotation(addCustomModelAttr) || @within(addCustomModelAttr)")
public void addModelAttributes(JoinPoint joinPoint, AddCustomModelAttr addCustomModelAttr) {
// 尝试从方法参数中获取Model对象
Object[] args = joinPoint.getArgs();
Model model = null;
for (Object arg : args) {
if (arg instanceof Model) {
model = (Model) arg;
break;
}
}
// 如果方法参数中没有Model对象,则尝试从ModelAndView中获取(如果返回类型是ModelAndView)
// 或者通过其他方式(如RequestAttributes)来传递数据。
// 这里为了示例的简洁性,我们假设Model总是作为参数传入。
if (model == null) {
// 尝试从请求属性中获取Model,这通常不是直接获取Model的最佳方式,
// 但可以作为一种备选方案或用于调试。
// 实际场景中,如果Model不是参数,可能需要改变切点或通知类型。
System.out.println("警告:目标方法没有Model参数,无法直接添加属性。");
return;
}
// 获取注解的属性值
String key = addCustomModelAttr.key();
String value = addCustomModelAttr.value();
// 向Model中添加属性
model.addAttribute(key, value);
System.out.println("AOP: 成功向Model中添加属性 - key: " + key + ", value: " + value);
}
}切面说明:
获取 Model 对象的注意事项: 在Web环境中,Model 对象通常作为 Controller 方法的参数由Spring自动注入。上述切面通过遍历 JoinPoint 的参数来获取 Model。如果目标方法没有 Model 参数,或者 Model 是通过其他方式(如 ModelAndView 返回值)处理的,那么上述获取 Model 的逻辑可能需要调整。对于更复杂的场景,可能需要使用 RequestContextHolder 获取当前请求,然后通过 HttpServletRequest 或 HttpServletResponse 来间接操作,或者将通知类型改为 @Around 并处理 ModelAndView 返回值。
现在,我们可以在Spring Boot的Controller方法或类上使用这个自定义注解了。
package com.example.demo.controller;
import com.example.demo.annotation.AddCustomModelAttr;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/ex")
public class ExController {
// 示例1:在方法上使用注解,使用默认的key和value
@AddCustomModelAttr
@GetMapping("/index1")
public String index1(Model model){
System.out.println("Controller: index1 方法执行,Model内容:" + model.asMap());
return "index"; // 假设存在一个名为 index.html 的Thymeleaf模板
}
// 示例2:在方法上使用注解,并指定自定义的key和value
@AddCustomModelAttr(key = "customKey", value = "customValue")
@GetMapping("/index2")
public String index2(Model model){
System.out.println("Controller: index2 方法执行,Model内容:" + model.asMap());
return "index";
}
// 示例3:在类上使用注解,所有方法都将继承该逻辑
// 为了演示,我们将这个注解移到类级别,并创建一个新的Controller
}
@AddCustomModelAttr(key = "classLevelKey", value = "classLevelValue")
@Controller
@RequestMapping("/class-level")
class ClassLevelAnnotatedController {
@GetMapping("/home")
public String home(Model model) {
System.out.println("Controller: home 方法执行,Model内容:" + model.asMap());
return "index";
}
@GetMapping("/about")
public String about(Model model) {
System.out.println("Controller: about 方法执行,Model内容:" + model.asMap());
return "index";
}
}Controller说明:
在Spring Boot应用中,通常无需手动配置,Spring Boot会自动检测到类路径下的AspectJ库和 @Aspect 注解,并自动启用AOP代理。如果你的项目没有自动启用AOP,你可以在主应用类上添加 @EnableAspectJAutoProxy 注解。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy // 如果AOP没有自动启用,则需要添加此注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}启动Spring Boot应用,并访问 /ex/index1、/ex/index2、/class-level/home 或 /class-level/about 等URL。你会在控制台看到切面输出的日志,以及Controller方法中打印的 Model 内容,验证自定义属性是否已成功添加。
例如,访问 /ex/index1 后,控制台可能会输出:
AOP: 成功向Model中添加属性 - key: defaultKey, value: defaultValue
Controller: index1 方法执行,Model内容:{defaultKey=defaultValue}这表明,在 index1 方法实际执行之前,切面已经介入并向 Model 中添加了 defaultKey:defaultValue。
通过自定义注解和Spring AOP,我们成功实现了在不修改业务方法代码的前提下,动态地向方法中注入特定逻辑。这种方式极大地提高了代码的模块化和复用性。
注意事项:
这种模式不仅限于向 Model 添加属性,还可以用于实现权限校验、数据审计、缓存管理、事务控制等各种横切关注点,是Spring框架中一个非常强大且常用的特性。
以上就是利用自定义注解在Spring Boot中实现方法逻辑的动态增强的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号