0

0

在Spring Boot中通过自定义注解实现方法逻辑动态增强

聖光之護

聖光之護

发布时间:2025-09-22 12:28:27

|

366人浏览过

|

来源于php中文网

原创

在spring boot中通过自定义注解实现方法逻辑动态增强

本文深入探讨了如何在Spring Boot应用中利用自定义注解和Spring AOP(面向切面编程)来动态地为特定方法或类注入额外逻辑。通过创建自定义注解、定义切面以及编写环绕通知,我们能够实现对目标方法的行为进行前置、后置或完全替换的控制,从而优雅地解决跨领域关注点问题,增强代码的可维护性和扩展性。

1. 引言:自定义注解与逻辑增强的需求

在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能够通过反射读取注解的关键。

3.2 步骤二:创建切面(Aspect)

接下来,创建一个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)。

3.3 步骤三:应用自定义注解

现在,我们可以在Spring Controller或其他组件的方法或类上使用@MyCustomAnnotation了。

Copy Leaks
Copy Leaks

AI内容检测和分级,帮助创建和保护原创内容

下载
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 配置:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.18 
         
    
    com.example
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot

    
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                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);
    }

}

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框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

102

2025.08.06

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

135

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

389

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

68

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

33

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

114

2025.12.24

html版权符号
html版权符号

html版权符号是“©”,可以在html源文件中直接输入或者从word中复制粘贴过来,php中文网还为大家带来html的相关下载资源、相关课程以及相关文章等内容,供大家免费下载使用。

609

2023.06.14

html在线编辑器
html在线编辑器

html在线编辑器是用于在线编辑的工具,编辑的内容是基于HTML的文档。它经常被应用于留言板留言、论坛发贴、Blog编写日志或等需要用户输入普通HTML的地方,是Web应用的常用模块之一。php中文网为大家带来了html在线编辑器的相关教程、以及相关文章等内容,供大家免费下载使用。

646

2023.06.21

Golang gRPC 服务开发与Protobuf实战
Golang gRPC 服务开发与Protobuf实战

本专题系统讲解 Golang 在 gRPC 服务开发中的完整实践,涵盖 Protobuf 定义与代码生成、gRPC 服务端与客户端实现、流式 RPC(Unary/Server/Client/Bidirectional)、错误处理、拦截器、中间件以及与 HTTP/REST 的对接方案。通过实际案例,帮助学习者掌握 使用 Go 构建高性能、强类型、可扩展的 RPC 服务体系,适用于微服务与内部系统通信场景。

8

2026.01.15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 2.5万人学习

C# 教程
C# 教程

共94课时 | 6.8万人学习

Java 教程
Java 教程

共578课时 | 46.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号