posts - 431,  comments - 344,  trackbacks - 0

使用handler(TypePattern)切入点。语法:
pointcut <pointcut name>(<any values to be picked uo>) : handler(<class>) ;
handler(TypePattern)切入点只支持vbefore()形式的通知。这意味着不能使用像around()这样的通知来重写catch块的正常行为。

public aspect HandlerRecipe {
 pointcut myExceptionHandlerPointcut() : handler(ServiceException);
 before() : myExceptionHandlerPointcut() {
  System.out.println("------------ Aspect Advice Logic --------------");
  System.out.println("Signature: " + thisJoinPoint.getStaticPart().getSignature());
  System.out.println("Source Line: " + thisJoinPoint.getStaticPart().getSourceLocation());
  System.out.println("-----------------------------------------------");
 }
}


public class ServiceException extends Exception {

 /**
  * Create a new ServiceException with the specified message.
  * @param msg the detail message
  */
 public ServiceException(String msg) {
  super(msg);
 }

 /**
  * Create a new ServiceException with the specified message
  * and root cause.
  * @param msg the detail message
  * @param ex the root cause
  */
 public ServiceException(String msg, Throwable ex) {
  super(msg, ex);
 }
}

public class ExceptionClass {

 public void triggerMyException() throws ServiceException
    {
  ServiceException myException = new ServiceException("A service exception has occured");
       System.out.println("About to throw a ServiceException");
       throw myException;
    }
 /**
  * @param args
  */
 public static void main(String[] args) {
  ExceptionClass myObject = new ExceptionClass();
   try
       {
          myObject.triggerMyException();
       } catch (ServiceException me)
       {
          System.out.println("A ServiceException has been caught");
       }
 }

}

运行结果:
About to throw a ServiceException
------------ Aspect Advice Logic --------------
Signature: catch(ServiceException)
Source Line: ExceptionClass.java:19
-----------------------------------------------
A ServiceException has been caught

获取抛出的异常
public aspect HandlerRecipe {
 pointcut myExceptionHandlerPointcut(ServiceException exception) : handler(ServiceException) && args(exception);
 before(ServiceException exception) : myExceptionHandlerPointcut(exception) {
  System.out.println("------------ Aspect Advice Logic --------------");
  System.out.println("Signature: " + thisJoinPoint.getStaticPart().getSignature());
  System.out.println("Source Line: " + thisJoinPoint.getStaticPart().getSourceLocation());
  System.out.println("Exception caught:");
  exception.printStackTrace();
  System.out.println("-----------------------------------------------");
 }
}

posted on 2007-07-03 16:32 周锐 阅读(288) 评论(0)  编辑  收藏 所属分类: AspectJ

只有注册用户登录后才能发表评论。


网站导航: