springboot用aop记录操作日志

第一次接触日志,慢慢看别人代码自学吧。今天看到了一个后台记录员工操作记录的功能感觉很6,边敲边学习学习。

建个项目加入以下三个依赖其中包括对aop的支持,这几个依赖不用多说了吧

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

然后搞个@Log注解,用来注解需要记录的类

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

来个切面(LogAspect)

@Aspect
@Component
public class LogAspect {
	@Pointcut("@annotation(test.Log)")
	public void logPointCut() {
	}

	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable, InterruptedException {
		System.out.println("=============================");
		Object result = point.proceed();
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method method = signature.getMethod();
		String name = method.getName();
		System.out.println("Method Name:" + name);//输出方法名
		Log log = method.getAnnotation(Log.class);
		System.out.println("Log Value:" + log.value());//输出注解里面的值
		System.out.println("+++++++++++++++++++++++++++++");
		return result;
	}
}

其中@Pointcut("@annotation(test.Log)")用于匹配当前执行方法持有指定注解的方法,这里我们指定的注解是之前自定义的@Log,其他逻辑没怎么写,主要是测试看看。

最后是控制器类

@Controller
public class TestController {
	@GetMapping("/index")
	@Log("this is index")
	public String index() {
		return "index";
	}

	@GetMapping("/success")
	@Log("this is success")
	public String success() {
		return "success";
	}

	@GetMapping("/test")
	@Log("this is test")
	public String test() {
		return "test";
	}

}

这里用@Log注解给每个方法添加不同的标记,运行项目,访问http://localhost:8080/index,控制台输出如下

=============================
Method Name:index
Log Value:this is index
+++++++++++++++++++++++++++++

okkkkkkkkkkkkkkkkkkkkkkkk

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值