使用@Aspect标签标注的类就是一个切面类
@Aspect
@Comment
public class CalculatorLoggingAspect{
private Log log = LogFactory.getLog(this.getClass());
@Before("execution(* ArithmeticCalculator.add(..))")
public void logBefore(JoinPoint jp){
Object[] args = jp.getArgs();
String methodName = jp.getSignature().getName();
log.info("The method add() begins");
}
}
@Before标识这个方法是个前置通知,切点表达式表示执行ArithmeticaCalculator借口的add()方法。
execution * com.spring.AritheticCalculator.*(..)
第一个*代表匹配任意修饰符及任意返回值,也可设置固定的返回参数如public int
第二个*代表任意方法
..在方法参数列表中使用,不限定类型。顺序。个数
@After标识与@Before使用方法相同,只是次切点是在连接点后面执行
注:无论此连接点方法是否能够正常执行,@After方法都会执行
@AfterReturning需要连接点方法正常返回之后才会执行
此标签后的returning参数的作用是告知spring要获取目标对象方法(被代理对象)返回值, result
通知的参数列表中,指定一个形参名字和returning属性中的名字一致
JoinPoint类型是框架中获取连接点详细信息的方法类
@AfterReturning(pointcut="exection(public int com.spring.aop.ComputerImpl1.*(..))",returning="result")
public void c(JoinPoint jp,Object result){
}
@AfterThrowing
@AfterThrowing(poincut="exection(public int com.spring.aop.ComputerImpl1.*(..))",throwing="ex")
public void d(JoinPoint jp,Exception ex){
Object[] args = jb.getArgs();
String methodName = jp.getSignature().getName();
System.out.println(“出现了异常”+ ex.getMessage());
}
环绕通知
是否执行这个连接点
环绕通知需要在通知方法的参数列表中,提供一个ProceedingJoinPoint接口类型参数的形参
@Around("exection(public int com.spring.aop.ComputerImpl1.*(..))")
public void e(ProceedingJoinPoint pjp){
pjp.getSingnature().getName()
try{
//前置通知
pjp.proceed();
//返回值通知
}catch(Throwable e1){
System.out.print("出现了异常");
e1.printStackTrac();
}
//后置通知
}
切面优先级
在切面前面添加一个@Order()标签在里面添加参数,参数值越小优先级越高
使用接口类来实现
public class ValidateAspect implements Ordered{
@Override
public int get Order(){
return 0
}
}
重用切入点表达式
写一个方法没有方法体
给方法加入一个@PointCut(“切点表达式”)
通知当中pointcut=”方法名称()”
@Aspect
@Comment
public class ComputerAspect{
@Pointcut("exection(public int com.spring.aop.ComputerImpl1.*(..))")
public void getExcecution(){
}
@Before("getExcecution()")
public void logBefore(JoinPoint jp){
Object[] args = jp.getArgs();
String methodName = jp.getSignature().getName();
}
}
基于xml形式配置AOP
一、习惯利用注解的方式来进行aop的配置,AOP框架兼容注解的,注解的方法有重用性
二、如何配置:
1)导入aop命名空间<aop:config></aop:config>
2)通过bean标签来完成目标对象以及切面实例的配置
3)
<aop:config>
<aop:pointcut expression="切点表达式" id=""/>
<aop:aspect id="" ref="引用的类的实例">
<aop:before method="方法名称" pointcut="具体的切入点"或 pointcur-ref="重用的切入点"
<aop:aspect>
<aop:config>
在项目的xml配置文件中配置<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
的标签
作用:用来自动生成所有被Aspect标注修饰的类生成代理对象
同样要在切面代理类和被代理类前面加入@Component标签,让spring扫描创建一个切面代理类的实例