当前位置: 首页 > article >正文

SpringBoot之自定义简单的注解和AOP

1.引入依赖

<!-- AOP依赖-->
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjweaver</artifactId>
	<version>1.9.8</version>
</dependency>

2.自定义一个注解

package com.example.springbootdemo3.annotation;

import java.lang.annotation.*;

@Target({ElementType.METHOD}) // 指定该注解可以加在方法上
@Retention(RetentionPolicy.RUNTIME) // 指定该注解在运行时保留,可以通过反射获取
@Documented // 表明该注解被包含在javadoc中
public @interface MyLog {

    /**
     * 名称
     */
    String name() default "";
}

3.自定义AOP

package com.example.springbootdemo3.aop;

import com.example.springbootdemo3.annotation.MyLog;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * description
 * 自定义ControllerAOP
 *
 * @author PC 2025/02/24 20:37
 */
@Component
@Aspect
public class MyControllerAop {
    // 定义使用MyLog注解的方法为切入点
    @Pointcut("@annotation(com.example.springbootdemo3.annotation.MyLog)")
    private void pointCut() {
    }

    @Around("pointCut()") // 注解表示该方法是一个环绕通知(around advice),它会在指定的切入点(pointcut)执行前后进行增强处理。
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取倍增强调的类和方法信息
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取被增强的方法对象
        Method method = methodSignature.getMethod();
        // 获取被增强的方法上的注解
        if (method != null) {
            MyLog myLog = method.getAnnotation(MyLog.class);
            System.out.println("MyLog name:" + myLog.name());
        }
        // 方法名
        String name = method.getName();
        System.out.println("方法名:" + name);

        // 获取Request对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 访问url
        String url = request.getRequestURL().toString();
        System.out.println("访问url:" + url);
        // 请求方式
        String method1 = request.getMethod();
        System.out.println("请求方式:" + method1);
        // 请求参数
        String queryString = request.getQueryString();
        System.out.println("请求参数:" + queryString);
        // 请求IP
        System.out.println("请求IP:" + getClientIpAddress(request));
        Object proceed = joinPoint.proceed();
        System.out.println("返回值:" + proceed);
        return proceed;
    }

    /**
     * 方法:获取真实IP地址
     * 从常见的IP所在的请头中来获取
     *
     * @param request
     * @return
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

3.写个测试Controller试一下

package com.example.springbootdemo3.config;

import com.example.springbootdemo3.annotation.MyLog;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * description
 *
 * @author PC 2025/02/24 21:29
 */
@RestController
@RequestMapping("/aop-test")
public class AopTestController {
    @PostMapping("/test")
    @MyLog(name = "aop测试")
    public String aopTest(@RequestBody Map map) {
        System.out.println(map);
        return "success";
    }
}

4.结束

在这里插入图片描述


http://www.kler.cn/a/560707.html

相关文章:

  • Ubuntu22.04 - etcd的安装和使用
  • [Android]APP自启动
  • Linux-Ansible基础模块
  • 监控与告警系统Prometheus
  • 一.Vue中的条件渲染
  • ELK之elasticsearch基本使用教程
  • 鸿蒙NEXT开发-文件服务上传下载
  • GitHub免密操作与跨服务器通行:SSH密钥一站式配置指南
  • 从零开始玩转TensorFlow:小明的机器学习故事 5
  • 再论Spring MVC中Filter和HandlerInterceptor的优先级
  • 工具方法 - 合规性矩阵
  • 登录-10.Filter-登录校验过滤器
  • 【Python爬虫(64)】从“听”开始:Python音频爬虫与语音数据处理全解析
  • 微信小程序——访问服务器媒体文件的实现步骤
  • 考研/保研复试英语问答题库(华工建院)
  • 网络安全-Mysql注入知识点
  • java基础面试-Java 内存模型(JMM)相关介绍
  • 《深度剖析Linux 系统 Shell 核心用法与原理_666》
  • [AI相关]问问DeepSeek如何基于Python,moviePy实现视频字幕功能
  • Java 新手宝典(带案例)