新建一个注解:
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,控制台输出: