6、advice

看两种advice
     after() returning() : pointcut_expression {}
     after() throwing() : pointcut_expression {}

HelloWorld.java

package aspectj;

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Teacher teacher=new Teacher();
        teacher.second();
        
    }

}

Teacher.java

package aspectj;

public class Teacher {

    public int  second()
    {
        System.out.println("second");
        
        return 1;
    }

}

HelloAspect.aj

package aspectj;

public aspect HelloAspect {
    

    pointcut PrintPointCut() : call(* aspectj.Teacher.second(..));
    
    after() returning( Object o): PrintPointCut() {
        System.out.println("拦截位置"+thisJoinPoint.getSourceLocation()+"object---"+o);
    }
    
}



输出:


6、advice_第1张图片
image.png

修改Teacher.java

package aspectj;

public class Teacher {

    public int  second()
    {
        System.out.println("second");
        int i=1/0;
        return 1;
    }

}

HelloAspect.aj

package aspectj;

public aspect HelloAspect {
    

    pointcut PrintPointCut() : call(* aspectj.Teacher.second(..));
    
     after() throwing (Exception e): PrintPointCut() {  
         System.out.println("拦截位置"+thisJoinPoint.getSourceLocation()+"exception---"+e); 
        } 
    
}



6、advice_第2张图片
image.png
around

Teacher.java

package aspectj;

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Teacher teacher=new Teacher();
        int value=teacher.second(2);
        System.out.println("main---"+value);
        
    }

}

HelloWorld.java

package aspectj;

public class HelloWorld {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Teacher teacher=new Teacher();
        int value=teacher.second(2);
        System.out.println("main---"+value);
        
    }

}

HelloAspect.aj

package aspectj;

public aspect HelloAspect {
    

    pointcut PrintPointCut(int x) : execution(* aspectj.Teacher.second(int))&&args(x);
    
    
     int around(int x) : PrintPointCut(x) {
         System.out.println("source---location---"+thisJoinPoint.getSourceLocation());
         System.out.println("pointcut----"+x);
         System.out.println(thisJoinPoint+"-------执行前");
         int newValue=proceed(x*3);
         System.out.println(thisJoinPoint+"-------执行后");
         return newValue;
     }
    
}



输出:


6、advice_第3张图片
image.png

你可能感兴趣的:(6、advice)