跟我学aspectj之九----- advice

 

    asepctj有5种类型的advice

  • before( Formals )
  • after( Formals ) returning [ ( Formal ) ]
  • after( Formals ) throwing [ ( Formal ) ]
  • after( Formals )
  • Type around( Formals )


  关于 前四种不想做过多的解释。before已经在我们之前的的Demo中用了无数次了,剩下的3个,我给一个基本的语法就可以了,用起来和before一样。

aspect A {
      pointcut publicCall(): call(public Object *(..));
      after() returning (Object o): publicCall() {
	  System.out.println("Returned normally with " + o);
      }
      after() throwing (Exception e): publicCall() {
	  System.out.println("Threw an exception: " + e);
      }
      after(): publicCall(){
	  System.out.println("Returned or threw an Exception");
      }
  }


   如果不太清楚的同学,可以自己把我们之前的Demo改进,看看结果便清楚。接下来,我们重点讲讲around通知:


       

package com.aspectj.demo.aspect;

import com.aspectj.demo.test.HelloAspectDemo;



public aspect HelloAspect {

	pointcut HelloWorldPointCut(int x) : execution(* main(int)) && !within(HelloAspectDemo) && args(x);
	
	
	
   int around(int x) : HelloWorldPointCut(x){
	  System.out.println("Entering : " + thisJoinPoint.getSourceLocation());
	  int newValue = proceed(x*3);
	  return newValue;
	}
}

package com.aspectj.demo.test;

public class HelloWorld {

	
	public static int main(int i){
		System.out.println("in the main method  i = " + i);
		return i;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		main(5);
	}

}


  最主要的就是 proceed()这个方法~ 重要的还是自己感觉一下吧。

你可能感兴趣的:(exception,String,object,Class,returning)