1. 程式人生 > >跟我學aspectj之九----- advice

跟我學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()這個方法~ 重要的還是自己感覺一下吧。