Spring Boot 使用注解和AOP实现记录日志功能

新建一个注解:

package com.springboot.annotation;

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

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

   这里使用了@interface声明了LogAnnotation 注解,并使用@Target注解传入ElementType.METHOD参数来标明@LogAnnotation 只能用于方法上,@Retention(RetentionPolicy.RUNTIME)则用来表示该注解生存期是运行时,  @Target和@Retention是由Java提供的元注解,所谓元注解就是标记其他注解的注解。
引入:

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>

新建一个切面:

package com.springboot.advice;

import com.springboot.annotation.LogAnnotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class LogAdvice {

    @Around(value = "@annotation(com.springboot.annotation.LogAnnotation)")
    public Object savaLog(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);


        // do something
        System.out.println(logAnnotation.value());
        System.out.println(methodSignature.getReturnType());
        System.out.println(methodSignature.getMethod());
        System.out.println(methodSignature.getName());
        System.out.println(methodSignature.getDeclaringTypeName());
        System.out.println(methodSignature.getDeclaringType());

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


        return object;
    }
}

新建controller类:

package com.springboot.controller;

import com.springboot.annotation.LogAnnotation;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/hello")
public class HelloController {

    @LogAnnotation("日志内容")
    @GetMapping("/{name}")
    public String sayHello(@PathVariable String name) {
        return "hello " + name;
    }
}

访问localhost:8090/hello/song,控制台输出: 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值