Springboot自定义注解打印方法入参

1. 背景

在开发过程中需要对程序进行大量的日志打印,其中就包括对方法入参以及返回值的打印,如果每个方法的入参以及出参都手动打印日志,不仅会有大量重复代码,同时代码会比较丑陋,可读性降低,所以需要一个切面来帮助打印日志,这时候就需要我们自己去定义一个自定义注解来做这件事了。

2. maven配置

首先需要在maven的pom文件中配置依赖。

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
</dependency>

3. 自定义注解

依赖配置好后,需要我们自定义一个注解。

@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogProfiler {

    /**
     * 方法英文名称,格式为:类名.方法名
     */
    String key() default "";

    /**
     * 方法中文名称,必填
     */
    String name();

    /**
     * 描述信息,非必填
     */
    String description() default "";

}

@Documented 将该自定义注解添加到 javadoc 文档中
@Target({ElementType.METHOD}) 该注解是作用在方法上的
@Retention(RetentionPolicy.RUNTIME) 作用时机为运行时

4. 配置AOP切面

定义好注解后,需要定义切面来解析该注解。

新建一个LogAspect

@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
}

声明切面

@Pointcut("@annotation(com.demo.common.annotation.LogProfiler)")
public void pointcut() {
}

配置环绕通知

@Around("pointcut()")
    public Object execParamLogAspect(ProceedingJoinPoint joinPoint) throws Throwable {
        // 如果停用日志打印,则直接执行原有代码逻辑,跳过打印日志
        if (!enable) {
            return joinPoint.proceed();
        }

        // 如果启用日志分析,则获取方法上的注解信息,并打印方法入参出参
        Method method = this.getMethod(joinPoint);
        LogProfiler logProfiler = method.getAnnotation(LogProfiler.class);
        // 获取注解上的 key+name
        String key = logProfiler.key();
        String name = logProfiler.name();
        String str = key + "-" + name;
        Object[] args = joinPoint.getArgs();
        // 打印入参
        this.printParam(str, args);
        // 执行原有方法逻辑
        Object result = joinPoint.proceed();
        // 打印出参
        this.printResult(str, result);
        return result;
    }

	private Method getMethod(JoinPoint jp) throws Exception {
        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        Method method = methodSignature.getMethod();
        return jp.getTarget().getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
    }

    /**
     * 打印入参
     *
     * @param key  方法名称
     * @param args 参数
     */
    private void printParam(String key, Object[] args) {
        if (log.isInfoEnabled()) {
            log.info("{}方法入参为:{}", key, JSONObject.toJSONString(args));
        }
    }

    /**
     * 打印出参
     *
     * @param key    方法名称
     * @param result 方法返回值
     */
    private void printResult(String key, Object result) {
        if (log.isInfoEnabled()) {
            log.info("{}方法出参为:{}", key, JSONObject.toJSONString(result));
        }
    }

其中enable为日志打印的全局开关,可以通过在application.yml中配置该属性来决定日志是否打印。默认值为true。

    @Value("${log.profiler.enable:true}")
    private Boolean enable;

5. 使用自定义注解打印

自定义注解定义完成,可以在我们的方法上面来使用这个注解了,使用如下图

请添加图片描述

调用该方法时,就可以看到该注解所打印的日志了

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当您想要将Spring Boot的启动横幅(Banner)修改为自定义注解方式时,可以按照以下步骤进行实现: 1. 创建一个注解类,用于标记需要修改横幅的类或方法。例如,创建一个名为`CustomBanner`的注解类: ```java import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface CustomBanner { } ``` 2. 创建一个Banner自定义处理类,用于根据注解来修改横幅。例如,创建一个名为`CustomBannerHandler`的类: ```java import org.springframework.boot.Banner; import org.springframework.boot.ResourceBanner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; public class CustomBannerHandler { public static void handleCustomBanner(Class<?> primarySource, String... args) { SpringApplication application = new SpringApplicationBuilder(primarySource) .banner(getCustomBanner()) .build(args); ConfigurableApplicationContext context = application.run(args); ApplicationContext applicationContext = context.getApplicationContext(); // 扫描自定义注解,并进行相应的操作 String[] beanNames = applicationContext.getBeanNamesForAnnotation(CustomBanner.class); for (String beanName : beanNames) { Object bean = applicationContext.getBean(beanName); // 在这里可以对标记了CustomBanner注解的类或方法进行相应的操作 // 例如,可以打印一些额外的信息或者执行一些初始化操作 System.out.println("CustomBanner: " + bean.getClass().getName()); } } private static Banner getCustomBanner() { // 这里可以根据需要指定自定义的横幅文件,例如使用文本文件作为横幅 return new ResourceBanner(CustomBannerHandler.class.getResource("/custom-banner.txt")); } public static void main(String[] args) { handleCustomBanner(SpringBootApplication.class, args); } } ``` 3. 创建一个自定义的横幅文件,例如将其命名为`custom-banner.txt`,并将其放置在项目的`resources`目录下。您可以在该文件中编写您想要显示的自定义横幅内容。 4. 在需要修改横幅的类或方法上添加`CustomBanner`注解。例如: ```java @SpringBootApplication @CustomBanner public class MyApplication { public static void main(String[] args) { CustomBannerHandler.handleCustomBanner(MyApplication.class, args); } } ``` 这样,当您运行`MyApplication`类时,将会使用自定义横幅文件中定义的内容作为启动横幅,并且标记了`CustomBanner`注解的类或方法也会被识别出来进行相应的操作。 请注意,以上代码仅为示例,您可以根据实际需求进行修改和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值