第一次接触日志,慢慢看别人代码自学吧。今天看到了一个后台记录员工操作记录的功能感觉很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
 
版权声明:本文为qq_39023116原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。