AOP进阶练习

本文介绍了如何使用AspectJ框架通过注解方式实现AOP的进阶练习,包括添加依赖、配置spring-service.xml以及各种通知类型的详细说明,如@AspectJ定义切面、@Pointcut定义切入点、@Before、@AfterReturning、@Around、@AfterThrowing和@After等注解的使用,旨在简化Spring配置文件,提升代码可读性和维护性。
摘要由CSDN通过智能技术生成

添加依赖:
<!-- 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值