public class NMSSubject implements Subject { Collection observers = new ArrayList(); public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { this.observers.remove(observer); } public void notifyObservers() { for (Iterator i = observers.iterator(); i.hasNext();) ((Observer) i.next()).update(this); } // Have AOP intercept the next call and in turn call into JNDI // The legacy code might have been reading from a file or database. // The intercepted code could call into JNDI or some other API // This can be used as a temporary measure to avoid an upgrade public String getNewData() { return "Data Set: "; // Call into JNDI here via AOP }}
public class UpgradeInterceptor implements Interceptor{ public Object intercept(Invocation invocation) throws Throwable { String methodName = getFullMethodName(invocation); System.out.println("Intercepted method name: " + methodName); // Call the intercepted method. Object result = invocation.proceed(); // Now call into JNDI to get some data Lookup aLookup = new Lookup(); // Add this data to the intercepted method result return (String) result + aLookup.DirectoryLookup("report.txt"); }}
Lookup类通过下面的代码使用命名服务来获取需要的对象(report.txt): // Create the initial context Context ctx = new InitialContext(env); // Look up an object Object obj = ctx.lookup(searchElement);