在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>