自定义注解打印入参、结果日志

1、自定义注解
package com.logPrint;

import java.lang.annotation.*;

/**
 * 自定义注解,用于打印业务日志
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
public @interface BusinessLog {
    /**
     * 功能描述
     */
    String description() default "";
}
2、自定义切面类
package com.logPrint;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    /**
     * 自定义切点
     */
    @Pointcut("@annotation(com.logPrint.BusinessLog)")
    public void logPointCut() {

    }

    /**
     * 自定义切面
     */
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String description = "";
        try {
            // 获取HttpServletRequest
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert requestAttributes != null;
            HttpServletRequest request = requestAttributes.getRequest();

            // 获取注解参数
            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            description = method.getAnnotation(BusinessLog.class).description();
            if (description == null || description.isEmpty()) {
                description = method.getName();
            }

            // 获取方法参数名以及参数值
            Map<String, Object> argList = getParams(joinPoint);

            // 打印日志
            log.info("业务日志:{},请求方法:{},请求参数:{}", description, request.getMethod(), JSON.toJSONString(argList));
        } catch (Exception e) {
            log.error("日志记录出错", e);
        }

        // 执行原方法
        Object result = joinPoint.proceed();

        // 打印响应日志
        log.info("业务日志:{},响应结果:{}", description, JSON.toJSONString(result));

        return result;
    }

    /**
     * 从 JoinPoint 中获取方法参数名和参数值
     *
     * @param joinPoint 切点对象
     * @return 参数名和参数值的Map
     */
    public static Map<String, Object> getParams(ProceedingJoinPoint joinPoint) {
        Map<String, Object> paramMap = new HashMap<>();

        // 获取方法参数名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = signature.getParameterNames();

        // 获取参数值
        Object[] parameterValues = joinPoint.getArgs();

        // 将参数名和参数值存入Map
        for (int i = 0; i < parameterNames.length; i++) {
            // 过滤掉HttpServletRequest、HttpServletResponse、MultipartFile参数类型
            if (parameterValues[i] instanceof HttpServletRequest || parameterValues[i] instanceof HttpServletResponse || parameterValues[i] instanceof MultipartFile) {
                continue;
            }
            paramMap.put(parameterNames[i], parameterValues[i]);
        }

        return paramMap;
    }
}
3、调试类
package com.logPrint;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/log")
public class LogController {

    @BusinessLog(description = "日志打印测试")
    @GetMapping(value = "/test")
    public Map<String, String> logTest(String message, String phone) {
        log.info("方法执行:log test message:{} phone:{}", message, phone);

        Map<String, String> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", "18");
        return map;
    }
}
4、测试结果

### 创建和使用带数的自定义注解 在Spring Boot中创建并使用带有数的自定义注解涉及几个关键步骤。这些步骤包括定义注解、配置组件扫描以及利用AOP或其他方式处理注解逻辑。 #### 定义自定义注解 首先,需要定义一个新的注解类,并指定其元数据属性。这可以通过`@interface`关键字完成。为了使该注解能够携带数,可以在定义时声明相应的成员变量。下面展示了一个简单的例子: ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; // 设置注解的作用范围为目标方法或字段级别 @Target({ ElementType.METHOD, ElementType.FIELD }) // 设定注解保留策略为运行时可见 @Retention(RetentionPolicy.RUNTIME) public @interface CustomAnnotation { // 注解可以接受字符串类型的数,默认为空串 String value() default ""; } ``` 此部分展示了如何定义一个名为`CustomAnnotation`的简单注解,它可以应用于方法或字段上,并允许传一个可选的字符串数[^1]。 #### 处理自定义注解 一旦定义好了注解,下一步就是决定在哪里以及怎样去读取这个注解的信息。对于大多数场景来说,最常用的方法之一是借助于面向切面编程(AOP),即通过编写AspectJ风格的切面来拦截被标记了特定注解的目标对象/行为。 这里给出一段基于AOP实现的例子,用于捕获任何带有上述自定义注解的方法调用,并打印出所附带的消息内容: ```java import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Component @Aspect public class AnnotationProcessor { @Before("@annotation(customAnnotation)") public void process(JoinPoint joinPoint, CustomAnnotation customAnnotation){ System.out.println("Intercepted method call with message: " + customAnnotation.value()); } } ``` 这段代码实现了对所有标注有`CustomAnnotation`的地方进行前置增强(`@Before`)的功能,每当匹配到这样的地方就会触发相应的行为——在这里是指向控制台输出一条信息[^2]。 #### 应用实例 最后一步是在实际业务逻辑里运用之前准备好的工具。比如在一个控制器(Controller)内部添加这样一个注解,并为其提供具体的数值: ```java @RestController @RequestMapping("/example") public class ExampleController { @CustomAnnotation(value="This is a test.") @GetMapping("/test") public ResponseEntity<String> getTest(){ return new ResponseEntity<>("Success", HttpStatus.OK); } } ``` 当访问路径 `/example/test` 时,除了正常的HTTP响应外,还会看到由前面提到的那个方面程序产生的额外日志条目,显示了来自注解内的消息文本[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值