简单说下,我对aop的了解,我也是个小白,就简单说下我自己个人的理解。aop它是面向切面编程,那什么是切面呢?一个程序正常执行,主体程序前后我们需要做一些操作,当然手动可以写,这个没问题,但是当主体程序多的时候,要在每个前后都加相同的操作,这个是不是就很繁琐了。现在我们把前后加的操作这个位置当做切入点,主体多的时候是不是就形成面了,在这个面我们写上公共的方法以供程序使用,我就是我理解的切面AOP。
1、全局使用
@Aspect
@Component
public class AopDemo {
@Pointcut("execution(public * com.example.springbootdemo..*Controller.*(..))")
public void aopTest(){}
@Before(value = "aopTest()")
public void before(JoinPoint joinPoint){
System.out.println("调用方法前调用------------------");
}
@After(value = "aopTest()")
public void after(){
System.out.println("调用方法后调用------------------");
}
@AfterReturning(value = "aopTest()")
public void afterReturning(){
System.out.println("返回后调用");
}
}
其中@Pointcut决定使用的地方
2、自定义
接口:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnno {
}
实现
@Component
@Aspect
public class AnnoAopDemo {
@Pointcut("@annotation(com.example.springbootdemo.module.annotation.TestAnno)")
public void annoDemo(){
}
@Around(value="annoDemo()")
public void round(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("这里是方法的附近");
joinPoint.proceed();
}
}
使用
@RequestMapping("annoTest")
@TestAnno
public void annoTest(){
System.out.println("测试自定义注解");
}
执行结果