Spring使用注解实现aop前置通知,后置通知,异常通知

本文详细介绍了如何在Spring框架中使用注解配置AOP(面向切面编程),包括开启AOP支持、定义切面类、应用各种类型的通知(如前置、后置、异常和环绕通知),以及如何通过JoinPoint获取目标对象、方法和参数信息。

在SpringIOC容器中开启注解对AOP的支持<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
在通知类前面加上注解@Aspect
前置通知@Before()
后置通知@AfterReturning()
异常通知 @AfterThrowing()
环绕通知@Around()
在括号中,添加对应业务类的方法,要些全部的方法名
当括号中有多个方法名的时候,用key和value表示,并用逗号隔开

当需要获得对应业务类方法的一些属性的时候,可以使用JoinPoint来获取
目标对象getTarget()
目标方法getSignature().getName()
参数列表Arrays.toString(jp.getArgs())

注意:
通过注解形式  将对象增加到ioc容器时   
需要设置扫描器<context:component-scan base-package="package all"></context:component-scan>

通知类

package all;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("aop")//将这个类纳入SpringIOC容器
@Aspect//此类时通知了
public class aop {
	//前置通知
    @Before("execution(public String service.studentService.addstudent())")//属性:定义切点
	public void aopBefore(JoinPoint jp) {
    	
		System.out.println("注解形式的前置通知"+"目标对象"+jp.getTarget()+"目标对象"+jp.getSignature().getName()+"参数列表"+Arrays.toString(jp.getArgs()));
	}
    
    //后置通知
    @AfterReturning(pointcut = "execution(public String service.studentService.addstudent())",returning = "returnValue")
    public void aopAfter( Object returnValue)
    {
    	System.out.println("注解形式的后置通知");
    	System.out.println("注解形式的返回值"+returnValue);
    }
  
    //异常通知
    @AfterThrowing
    public void aopException() {
    	System.out.println("注解形式的异常通知");
    }
   
}

 SpringIOC

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<context:component-scan base-package="package all"></context:component-scan>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值