SpringAOP的注解方式

时间:2023-03-09 01:31:06
SpringAOP的注解方式

AOP(注解)【理解】【应用】【重点】

1.AOP注解配置流程

A.开启AOP配置支持注解@aspectj

核心配置文件中添加以下配置,功能等同于注解配置Bean的自动扫描路径

<aop:aspectj-autoproxy/>

B.将所有参与AOP配置的类声明为Spring控制的Bean

可以使用XML配置格式或注解格式

C.在切面类的类定义上方添加切面的声明

@Aspect

public class MyAdvice {…}

D.将切面类中的方法配置为指定类型的通知,配置时指定其切入点

@Before("execution(* cn.itcast.aop.annotation.UserImpl.add())")

public void before(JoinPoint jp) {

System.out.println("before");

}

2.配置公共的切入点

A.在切面类中声明一个方法(私有的),将该方法配置为切入点

@Pointcut("execution(* cn.itcast.aop.annotation.UserImpl.add())")

private void pt(){}

B.使用配置的切入点

@Before("引用切入点")

格式:切面类名.方法名()

范例:@Before("MyAdvice. pt ()")

3.注解开发通知的通知类别

前置通知              @Before(value="execution(* *..*.*(..))")

后置通知              @After(value="execution(* *..*.*(..))")

抛出异常通知       @AfterThrowing(value="execution(* *..*.*(..))",throwing="ex")

返回后通知           @AfterReturning(value="execution(* *..*.*(..))",returning="ret")

环绕通知              @Around(value="execution(* *..*.*(..))")

4.注解格式AOP顺序

总体顺序由上到下为下列描述顺序

around before

before

around after

after

afterReturning

实际开发以最终运行顺序为准

5.返回值与异常对象的获取方式

@AfterReturning(value="MyAdvice.pt()",returning="aa")

public void afterReturning(JoinPoint jp,Object aa){

System.out.println("afterReturning......."+aa);

}