aop:面向切面编程,可以看作是面向对象的补充
举例

<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.7.1version>
<relativePath/>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-aopartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.28version>
dependency>
dependencies>
/**
* @author wyr
* @version 1.0
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysLog {
/**
* 描述
*
* @return {String}
*/
String value() default "";
}
@Slf4j
@Aspect
@Component
public class SysLogAspect {
//定义切点 值为注解的全路径 拦截所有使用了拦截SysLog注解的方法
@Pointcut("@annotation(com.example.demo.annotation.SysLog)")
public void sysLogAspect() {
}
@Around(value="sysLogAspect()") //直接value="@annotation(com.example.demo.annotation.SysLog)"也可以
public Object around(ProceedingJoinPoint point){
Object proceed = null;
try {
//使用注解的方法执行之前 相等于 @before
//获取类名
String className = point.getTarget().getClass().getName();
//获取执行的方法名
String methodName = point.getSignature().getName();
//获取参数
Object[] args = point.getArgs();
//获取方法上注解的值
MethodSignature methodSignature = (MethodSignature)point.getSignature();
String annotationVal= methodSignature.getMethod().getAnnotation(SysLog.class).value();
log.info("[类名]:{},[方法]:{},[参数]:{},[操作]:{}", className, methodName, JSON.toJSONString(args),annotationVal);
//相等于放行 如果直接return 则不执行使用了该注解对应的方法
System.out.println("方法执行之前");
proceed = point.proceed();
System.out.println("方法执行之后");
//使用注解的方法之后
System.out.println("方法的返回值是:"+proceed);
} catch (Throwable e) {
throw new RuntimeException(e.getMessage());
}
return proceed;
}
}
@RestController
public class UserController {
@GetMapping("/test/{name}")
@SysLog("操作是获取名称")
public String test(@PathVariable("name") String name){
System.out.println("方法开始执行");
return "我是返回值";
}
}