SpringBoot:SpringBoot通过注解监测Controller接口

简介: 本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。

SpringBoot:通过注解监测Controller接口

在Spring Boot应用中,通过注解监测Controller接口是一种常见且有效的方式,用于记录接口的访问日志、性能监控、异常处理等。本文将详细介绍如何使用Spring Boot注解来监测Controller接口,并提供一个完整的示例。

一、基本概念

1.1 Spring AOP

Spring AOP(面向切面编程)是实现注解监测的重要技术。AOP可以在方法执行的各个阶段(如前后)添加额外的功能,而不需要修改方法本身。常用的AOP术语包括:

  • 切面(Aspect) :包含切入点和通知的模块。
  • 切入点(Pointcut) :定义在哪些地方应用通知。
  • 通知(Advice) :定义具体的横切逻辑,如日志记录。

1.2 自定义注解

自定义注解是标记Controller方法的基础,通过注解可以灵活地应用不同的监控策略。

二、实现步骤

2.1 创建自定义注解

首先,创建一个自定义注解,用于标记需要监测的Controller方法。

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Monitor {
    String value() default "";
}
​

2.2 创建AOP切面

接下来,创建一个AOP切面,拦截带有 @Monitor注解的方法,并添加监测逻辑。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MonitorAspect {

    @Around("@annotation(monitor)")
    public Object around(ProceedingJoinPoint joinPoint, Monitor monitor) throws Throwable {
        long start = System.currentTimeMillis();

        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            return result;
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("Method [" + joinPoint.getSignature() + "] executed in " + (end - start) + " ms");
        }
    }
}
​

2.3 应用注解到Controller

在Controller的方法上应用自定义注解 @Monitor

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class DemoController {

    @Monitor("Example monitoring")
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}
​

2.4 配置Spring Boot应用

确保Spring Boot应用启用了AOP功能,可以在 application.properties中进行必要配置。

spring.aop.auto=true
spring.aop.proxy-target-class=true
​

三、示例代码

以下是一个完整的示例代码,包含自定义注解、AOP切面和Controller:

3.1 自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Monitor {
    String value() default "";
}
​

3.2 AOP切面

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MonitorAspect {

    @Around("@annotation(monitor)")
    public Object around(ProceedingJoinPoint joinPoint, Monitor monitor) throws Throwable {
        long start = System.currentTimeMillis();

        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            return result;
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("Method [" + joinPoint.getSignature() + "] executed in " + (end - start) + " ms");
        }
    }
}
​

3.3 Controller

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class DemoController {

    @Monitor("Example monitoring")
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}
​

3.4 Spring Boot 配置

spring.aop.auto=true
spring.aop.proxy-target-class=true
​

四、扩展应用

4.1 参数和返回值日志

除了记录执行时间,还可以记录方法的输入参数和返回值。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MonitorAspect {

    @Around("@annotation(monitor)")
    public Object around(ProceedingJoinPoint joinPoint, Monitor monitor) throws Throwable {
        long start = System.currentTimeMillis();

        Object result = null;
        try {
            // 记录方法输入参数
            Object[] args = joinPoint.getArgs();
            System.out.println("Method [" + joinPoint.getSignature() + "] called with arguments: " + Arrays.toString(args));

            // 执行目标方法
            result = joinPoint.proceed();

            // 记录方法返回值
            System.out.println("Method [" + joinPoint.getSignature() + "] returned: " + result);
            return result;
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("Method [" + joinPoint.getSignature() + "] executed in " + (end - start) + " ms");
        }
    }
}
​

4.2 异常处理

在AOP切面中还可以添加异常处理逻辑,捕获并记录方法执行中的异常。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MonitorAspect {

    @Around("@annotation(monitor)")
    public Object around(ProceedingJoinPoint joinPoint, Monitor monitor) throws Throwable {
        long start = System.currentTimeMillis();

        Object result = null;
        try {
            // 记录方法输入参数
            Object[] args = joinPoint.getArgs();
            System.out.println("Method [" + joinPoint.getSignature() + "] called with arguments: " + Arrays.toString(args));

            // 执行目标方法
            result = joinPoint.proceed();

            // 记录方法返回值
            System.out.println("Method [" + joinPoint.getSignature() + "] returned: " + result);
            return result;
        } catch (Throwable throwable) {
            // 记录异常
            System.err.println("Method [" + joinPoint.getSignature() + "] threw an exception: " + throwable);
            throw throwable;
        } finally {
            long end = System.currentTimeMillis();
            System.out.println("Method [" + joinPoint.getSignature() + "] executed in " + (end - start) + " ms");
        }
    }
}
​

五、总结

本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。

目录
相关文章
|
7天前
|
机器学习/深度学习 人工智能 自然语言处理
PAI Model Gallery 支持云上一键部署 DeepSeek-V3、DeepSeek-R1 系列模型
DeepSeek 系列模型以其卓越性能在全球范围内备受瞩目,多次评测中表现优异,性能接近甚至超越国际顶尖闭源模型(如OpenAI的GPT-4、Claude-3.5-Sonnet等)。企业用户和开发者可使用 PAI 平台一键部署 DeepSeek 系列模型,实现 DeepSeek 系列模型与现有业务的高效融合。
|
7天前
|
人工智能 搜索推荐 Docker
手把手教你使用 Ollama 和 LobeChat 快速本地部署 DeepSeek R1 模型,创建个性化 AI 助手
DeepSeek R1 + LobeChat + Ollama:快速本地部署模型,创建个性化 AI 助手
2578 111
手把手教你使用 Ollama 和 LobeChat 快速本地部署 DeepSeek R1 模型,创建个性化 AI 助手
|
2天前
|
云安全 边缘计算 人工智能
对话|ESA如何助力企业高效安全开展在线业务?
ESA如何助力企业安全开展在线业务
1014 7
|
4天前
|
人工智能 自然语言处理 JavaScript
宜搭上新,DeepSeek 插件来了!
钉钉宜搭近日上线了DeepSeek插件,无需编写复杂代码,普通用户也能轻松调用强大的AI大模型能力。安装后,平台新增「AI生成」组件,支持创意内容生成、JS代码编译、工作汇报等场景,大幅提升工作效率。快来体验这一高效智能的办公方式吧!
1301 5
|
14天前
|
Linux iOS开发 MacOS
deepseek部署的详细步骤和方法,基于Ollama获取顶级推理能力!
DeepSeek基于Ollama部署教程,助你免费获取顶级推理能力。首先访问ollama.com下载并安装适用于macOS、Linux或Windows的Ollama版本。运行Ollama后,在官网搜索“deepseek”,选择适合你电脑配置的模型大小(如1.5b、7b等)。通过终端命令(如ollama run deepseek-r1:1.5b)启动模型,等待下载完成即可开始使用。退出模型时输入/bye。详细步骤如下图所示,轻松打造你的最强大脑。
9349 86
|
2天前
|
人工智能 自然语言处理 API
DeepSeek全尺寸模型上线阿里云百炼!
阿里云百炼平台近日上线了DeepSeek-V3、DeepSeek-R1及其蒸馏版本等六款全尺寸AI模型,参数量达671B,提供高达100万免费tokens。这些模型在数学、代码、自然语言推理等任务上表现出色,支持灵活调用和经济高效的解决方案,助力开发者和企业加速创新与数字化转型。示例代码展示了如何通过API使用DeepSeek-R1模型进行推理,用户可轻松获取思考过程和最终答案。
|
6天前
|
API 开发工具 Python
阿里云PAI部署DeepSeek及调用
本文介绍如何在阿里云PAI EAS上部署DeepSeek模型,涵盖7B模型的部署、SDK和API调用。7B模型只需一张A10显卡,部署时间约10分钟。文章详细展示了模型信息查看、在线调试及通过OpenAI SDK和Python Requests进行调用的步骤,并附有测试结果和参考文档链接。
1246 7
阿里云PAI部署DeepSeek及调用
|
1月前
|
供应链 监控 安全
对话|企业如何构建更完善的容器供应链安全防护体系
阿里云与企业共筑容器供应链安全
171375 18
|
1月前
|
供应链 监控 安全
对话|企业如何构建更完善的容器供应链安全防护体系
随着云计算和DevOps的兴起,容器技术和自动化在软件开发中扮演着愈发重要的角色,但也带来了新的安全挑战。阿里云针对这些挑战,组织了一场关于云上安全的深度访谈,邀请了内部专家穆寰、匡大虎和黄竹刚,深入探讨了容器安全与软件供应链安全的关系,分析了当前的安全隐患及应对策略,并介绍了阿里云提供的安全解决方案,包括容器镜像服务ACR、容器服务ACK、网格服务ASM等,旨在帮助企业构建涵盖整个软件开发生命周期的安全防护体系。通过加强基础设施安全性、技术创新以及倡导协同安全理念,阿里云致力于与客户共同建设更加安全可靠的软件供应链环境。
150313 32
|
5天前
|
缓存 自然语言处理 安全
快速调用 Deepseek API!【超详细教程】
Deepseek 强大的功能,在本教程中,将指导您如何获取 DeepSeek API 密钥,并演示如何使用该密钥调用 DeepSeek API 以进行调试。

热门文章

最新文章