您的位置:jsp学习站首页 >> 应用服务器 >> JBoss >> 面向方面编程AOP和JBoss(二)

面向方面编程AOP和JBoss(二) (1)

[ 来源:互网络 | 更新日期:2007-10-05 06:23:59 | 浏览次数:1018]
简介:getMetaData(tracing, filter);   if (filter != null && filter
访问Metadata
为了用元数据,它在运行时间必须是可达的。类的元数据是通过Invocation对象可达的。为了在我们的例子使用它,TracingInterceptor必须要修改一点点。

public class TracingInterceptor implements Interceptor
{
  public String getName() { return TracingInterceptor; }
  public InvocationResponse invoke(Invocation invocation)
    throws Throwable
  {
   String filter = (String)invocation.getMetaData(tracing, filter);
   if (filter != null && filter.equals(true))
  return invocation.invokeNext();

   String message = null;

   if (invocation.getType() == InvocationType.METHOD)
   {
     Method method = MethodInvocation.getMethod(invocation);
     message    = method: + method.getName();
   }
   else if (invocation.getType() == InvocationType.CONSTRUCTOR)
   {
     Constructor c = ConstructorInvocation.getConstructor(invocation);
     message    = constructor: + c.toString();
   }
   else
   {
     // Do nothing for fields. Just too verbose.
     return invocation.invokeNext();
   }

   System.out.println(Entering + message);

   // Continue on. Invoke the real method or constructor.
   InvocationResponse rsp = invocation.invokeNext();
   System.out.println(Leaving + message);
   return rsp;
  }
}

运行例子2
[code]POJO类将扩展一点,增加get()和set()方法。
public class POJO
{
  public POJO() {}
  public void helloWorld() { System.out.println(Hello World!); }

  private int counter = 0;

  public int getCounter() { return counter; }
  public void setCounter(int val) { counter = val; }
  public static void main(String[] args)
  {
   POJO pojo = new POJO();
   pojo.helloWorld();
   pojo.setCounter(32);
   System.out.println(counter is: + pojo.getCounter());
  }
}
TracingInterceptor将拦截对main(),POJO()和helloWorld()调用。输出应该看起来如下:
Entering constructor: public POJO()
Leaving constructor: public POJO()
Entering method: helloWorld
Hello World!
Leaving method: helloWorld
[/code]

你能够在这里下载JBoss AOP和离子代码。编译和执行:
$ cd oreilly-aop/example2
$ export CLASSPATH=.;jboss-common.jar;jboss-aop.jar;javassist.jar
$ javac *.java
$ java -Djava.system.class.loader=org.jboss.aop.standalone.SystemClassLoader POJO

例子3.使用导言
如果我们能够为特定的实例关闭和打开,那将很酷。JBoss AOP有一个API,他绑定元数据到一个对象实例,但是让我们伪装一个实际的跟踪API是一个更好的方案。在这例子中,我们通过用一个导言,将改变POJO类的本身的定义。我们将强制POJO类去实现一个跟踪借口和提供混合类,这个混合类处理新的跟踪API。这将是跟踪借口:

public interface Tracing
{
  public void enableTracing();
  public void disableTracing();
}

定义一个混合的类
Tracing接口将在混合类中实现。当一
[1] [2] [3]
Tags:关键字:面向方面编程AOP和JBoss(二)
责任编辑:glen