• 注册
当前位置:1313e > 默认分类 >正文

AOP进阶练习

文章目录

        • 添加依赖:
        • 配置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。

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 162202241@qq.com 举报,一经查实,本站将立刻删除。

最新评论

欢迎您发表评论:

请登录之后再进行评论

登录
相关推荐