spring中的aop如何使用
1.AOP的使用场景
在实际工作中,可能会存在需要在调用方法前后做一些处理,例如:
1>调用业务方法前,检验入参信息,来决定后续方法执行的逻辑;
2>调用业务方法后,日志信息的记录等。
2.JoinPoint 介绍
JointPoint是程序运行过程中可识别的点,这个点可以用来作为AOP切入点。JointPoint对象则包含了和切入相关的很多信息。比如切入点的对象,方法,属性等。
aop的简单使用
1>引入注解:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
package com.atguigu.mybatisplus.AOP;
2>创建注解:
package com.atguigu.mybatisplus.AOP;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnno {
}
2>编写切面逻辑:
package com.atguigu.mybatisplus.AOP;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class VerifyAnnoAspect {
@Pointcut("@annotation(com.atguigu.mybatisplus.AOP.TestAnno)")
public void point(){}
@Around(value = "point()")
public void around(ProceedingJoinPoint joinPoint)throws Throwable{
System.out.println("环绕方法执行前。。。");
joinPoint.proceed();//调用要切的方法
System.out.println("环绕方法后......");
}
@Before("point()")
public void before() {
System.out.println("调用方法前执行。。。");
}
@After(value = "point()")
public void after(JoinPoint joinPoint)throws Throwable{
System.out.println("调用方法后执行。。。");
}
@AfterReturning(value = "point()")
public void afterReturning(JoinPoint joinPoint)throws Throwable{
System.out.println("调用方法返回结果后执行。。。");
}
}
4.编写controller
package com.atguigu.mybatisplus.AOP;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping ("/aaa")
@TestAnno
public void aaa(){
System.out.println("测试的方法");
}
}
5.测试:
输入localhost:80800/aaa
结果:
环绕方法执行前。。。
调用方法前执行。。。
测试的方法
调用方法返回结果后执行。。。
调用方法后执行。。。
环绕方法后......