spring框架基于注解aop的通知

来源:互联网 发布:淘宝联盟高佣金多少 编辑:程序博客网 时间:2024/06/06 11:39

张义胜的学习笔记

                 **之spring框架aop的通知**  

1.spring有两大基石,即IOC容器和AOP切面
2.Aop切面有5个通知:Before(前置通知),After(后置通知),AfterReturning(方法正常结束后的通知),AfterThrowing(异常通知),Around(环绕通知)
3.每个通知后面必须跟一个方法
4.在进行使用代理时,必须在IOC 容器中加入代码,该代码作用是在调用该对象时动态创建一个代理对象。我们须在切面类中加入@Aspect声明为一个切面,@Component将该对象加入IOC容器进行管理。
5.以用@order指定切面的优先级,值越小优先级越高

                 用法

1.Before:首先Before(“execution(public 方法返回值类型 类路径名.(,*))”)
。后面的方法中可以带参数JoinPoint joinpoint连接点,一个方法就是一个连接点,可以
根据参数获取方法名,以及传入的参数。
2.After与Before类似
3.AfterReturning,与之前的两个通知有所不同,在AfterReturning中须指明参数returning,即所调用方法的返回值。声明如下@AfterReturning(value=”execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”,returning=”result”)
。在这里需注意returning的参数result要与后面声明的方法的参数一样。
4.AfterThrowing与AfterReturning类似,需把returning改为throwing。
5.Around相当于前面4个通知的合并

                示例

@Component
public class AtithemeticCalculatorIMP implements AtithemeticCalculator{

@Overridepublic int add(int i, int j) {    // TODO Auto-generated method stub    int result=i+j;    return result;}@Overridepublic int sub(int i, int j) {    // TODO Auto-generated method stub    int result=i-j;    return result;}@Overridepublic int mul(int i, int j) {    // TODO Auto-generated method stub    int result=i*j;    return result;}@Overridepublic int div(int i, int j) {        int result=i/j;        return result;}@Overridepublic double as(double i, double j) {    return i+j;}

}
/**
* 每个通知后都必须跟一个方法
* 可以用@order指定切面的优先级,值越小优先级越高*/
@Aspect
@Component
public class LoggingAspect {
//前置通知:目标方法执行之前执行的代码
@Before(“execution(public * com.zhangyisheng.aop.AtithemeticCalculator.(,*))”)
public void beforeMethod(JoinPoint joinpoint)
{
String methodName=joinpoint.getSignature().getName();
Listargs=Arrays.asList(joinpoint.getArgs());
System.out.println(“the method “+methodName+” begin with”+args);
}
//后置通知:目标方法执行之后执行的代码
@After(“execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”)
public void after(JoinPoint joinpoint)
{ String methodName=joinpoint.getSignature().getName();
System.out.println(“the method “+methodName+” end”);
}
@AfterReturning(value=”execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”,returning=”result”)
public void afterReturning(JoinPoint joinpoint,Object result)
{ //正常结束后执行的代码
String methodName=joinpoint.getSignature().getName();
System.out.println(“the method “+methodName+” end width “+result);
}
@AfterThrowing(value=”execution(* com.zhangyisheng.aop.AtithemeticCalculator.(,*)))”,throwing=”e”)
public void afterThrowing(JoinPoint joinpoint,Exception e)
{
//异常时,执行的代码,两个参数e要一致
String methodName=joinpoint.getSignature().getName();
System.out.println(“the method “+methodName+” occus a error is “+e);
}
}

0 0
原创粉丝点击