文章目录
- 添加依赖:
- 配置spring-service.xml
- 基于注解的声明式AspectJ
添加依赖:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>5.2.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.5</version>
</dependency>
配置spring-service.xml
<!-- 启动基于注解的Aop -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
基于注解的声明式AspectJ
AspectJ框架为AOP的实现提供了一套注解,用以取代Spring配置文件为实现AOP功能所配置的臃肿代码。
@AspectJ 用于定义一个切面
//切面类
@Aspect
@Component
public class NotebookCountAOP {
}
@Pointcut 用于定义切入点表达式,还需要定义包含名字和任意参数的方法签名来表示切入点名称。
//切入点@Pointcut("execution (* com.whc.noteserver.service.NoteBookService.addNoteBook(..))")private void pointCut() {}
@Before 用于定义前置通知,相当于BeforeAdvice。在使用时,通常需要指定一个value属性值,该属性值用于指定一个切入点表达式。
@Before("pointCut()") public void before(JoinPoint joinPoint) {System.out.println("打印日志:addnotebook方法执行"); }
@AfterReturning 用于定义后置通知,相当于AfterReturningAdvice。
@AfterReturning("pointCut()") public void afterReturning(JoinPoint joinPoint){ System.out.println("'添加方法被执行"); }
@Around 用于定义环绕通知,相当于MethodInterceptor。在使用时需要指定一个value属性。该属性用于指定该通知被植入的切入点。
@Around("pointCut()")public Object around(ProceedingJoinPoint proceedingJoinPoint) {System.out.println("'环绕方法之前被执行");}
@AfterThrowing 用于定义异常通知来处理程序中未处理的异常,相当于ThrowAdvice。在使用时可指定pointcut/value和throwing属性。
@After 用于定义最终final通知,不管是否异常,该通知都会执行。在使用时需要指定一个value属性。该属性用于指定该通知被植入的切入点。
@DeclareParents 用于定义引价通知,相当于IntroductionInterceptor。