为了用元数据,它在运行时间必须是可达的。类的元数据是通过Invocation对象可达的。为了在我们的例子使用它,TracingInterceptor必须要修改一点点。
运行例子2, [code]POJO类将扩展一点,增加get()和set()方法。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; } }
TracingInterceptor将拦截对main(),POJO()和helloWorld()调用。输出应该看起来如下: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()); } }
你能够在这里下载JBoss AOP和离子代码。编译和执行:Entering constructor: public POJO() Leaving constructor: public POJO() Entering method: helloWorld Hello World! Leaving method: helloWorld [/code]
例子3.使用导言$ 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
如果我们能够为特定的实例关闭和打开,那将很酷。JBoss AOP有一个API,他绑定元数据到一个对象实例,但是让我们伪装一个实际的跟踪API是一个更好的方案。在这例子中,我们通过用一个导言,将改变 POJO类的本身的定义。我们将强制POJO类去实现一个跟踪借口和提供混合类,这个混合类处理新的跟踪API。这将是跟踪借口:
定义一个混合的类public interface Tracing { public void enableTracing(); public void disableTracing(); }
Tracing接口将在混合类中实现。当一个POJO是实例时,一个混合对象混合类将绑定到POJO类。下面是实现:
enableTracing()方法绑定filter属性到对象实例。在disableTracing()方法作同样的事,但是制定filter属性为false。这两个方法是元数据能够怎么样用于超过一个类级别。元数据也能够实例级的应用。元数据应用在实例级别。import org.jboss.aop.Advised; public class TracingMixin implements Tracing { Advised advised; Public TracingMixin(Object obj) { this.advised = (Advised)obj; } public void enableTracing() { advised._getInstanceAdvisor().getMetaData().addMetaData( "tracing", "filter", true); } public void disableTracing() { advised._getInstanceAdvisor().getMetaData().addMetaData( "tracing", "filter", false); } }