![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fb9c19b52ebe6451082fb7f76b958283.png)
springboot 的启动类
@SpringBootApplication
@RestController
public class XiaoLvTestApplication {
public static void main(String[] args) {
SpringApplication.run(XiaoLvTestApplication.class, args);
System.out.println("test启动");
}
}
一个controller
@RestController
public class AopController {
private static Logger logger = LoggerFactory.getLogger(AopController.class);
@GetMapping
public String test() {
logger.info("....test 正在处理....");
return "abc";
}
}
在这里插入代码片
/*
* aop 切面
* */
@Aspect
@Component
public class AopAspect {
private static Logger logger = LoggerFactory.getLogger(AopAspect.class);
// 切点
@Pointcut("execution(public * com.java110..*.*Controller.*(..)) ")
public void dataProcess() {
}
@Before("dataProcess()")
public void doBefore(JoinPoint joinPoint) throws Exception {
logger.info("-------------我处理之前-------------");
}
/*aop demo */
@AfterReturning(returning = "ret", pointcut = "dataProcess()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
}
//后置异常通知
@AfterThrowing("dataProcess()")
public void throwException(JoinPoint jp) {
}
@After("dataProcess()")
public void after(JoinPoint jp) throws IOException {
logger.info("-------------我处理完毕了-------------");
}
}
当访问项目 lcoahost:8080的时候
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e612bc2e42b132ab02e0f2453fd5c017.png)
我们还可以基于注解配置aop
从代码可以看出,切点指向的是个范围,在此范围内所有的方法都实现了Aop,在实际开发中我们可能只需要某各类中的某个方法实现aop,因此我们可以将切点Pointcut精确到某个方法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a2cba10cd92197bcbcf81c604b38b954.png)
赋 大佬的简述 https://www.jianshu.com/p/58d29f577cb4
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a6f2e36c7f6975e41038c2b1efa09f59.png)
可以先定义一个注解
package com.java110.test.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
/*
* aop
* */
@Aspect
@Component
public class AopAspect2 {
private static Logger logger = LoggerFactory.getLogger(AopAspect2.class);
@Pointcut(value = "@annotation(com.java110.test.config.LogDemo)")
public void dataProcess() {
}
@Before("dataProcess()")
public void doBefore(JoinPoint joinPoint) throws Exception {
logger.info("-------------我处理之前-------------");
}
@AfterReturning(returning = "ret", pointcut = "dataProcess()")
public void doAfterReturning(Object ret) throws Throwable {
// 处理完请求,返回内容
}
//后置异常通知
@AfterThrowing("dataProcess()")
public void throwException(JoinPoint jp) {
}
@After("dataProcess()")
public void after(JoinPoint jp) throws IOException {
logger.info("-------------我处理完毕了-------------");
}
}
以上 就只是切点 变了
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8c7cacf2e431116781d15b1343b2a9fe.png)
我们能看到同样的效果