开发上下文代理

使用工作管理器作为 ContextService,以便在上下文中调用接口。

关于此任务

要求在调用对象方法时存在线程上下文的应用程序组件可以使用工作管理器(它实现了 javax.enterprise.concurrent.ContextService)来构造对象的上下文代理。创建上下文代理时,将根据工作管理器的设置来捕获线程上下文。针对上下文代理调用接口方法时,将在调用之前应用先前捕获的线程上下文,并在调用后进行复原。

过程

  1. 定义一个具有需要线程上下文的方法的接口(或者选择合适的现有接口)。
    public interface AddressFinder {
        Address getAddress(Person p) throws Exception;
    }
  2. 提供该接口的实现:
    public class DatabaseAddressFinder implements AddressFinder {
        private final String resRefLookupName;
        public DatabaseAddressFinder(String resRefLookupName) {
            this.resRefLookupName = resRefLookupName;
        }
        public Address getAddress(Person p) throws Exception {
            // Resource reference lookup requires the thread context of the
            // application component that defines the resource reference.
            DataSource ds = (DataSource) new InitialContext().lookup(
                resRefLookupName);
            Connection con = ds.getConnection();
            try {
                ResultSet r = con.createStatement().executeQuery(
                    "SELECT STREETADDR, CITY, STATE, ZIP " +
                    "FROM ADDRESSES WHERE PERSONID=" + p.id);
                if (r.next())
                    return new Address(r.getString(1), r.getString(2),
                        r.getString(3), r.getInt(4));
                else
                    return null;
            } finally {
                con.close();
            }
        }
    }
  3. 使用上下文服务来捕获当前线程的上下文,并以该上下文包装实例:
    ContextService contextService = (ContextService) new InitialContext().lookup(
        "java:comp/DefaultContextService");
    AddressFinder addressFinder = contextService.createContextualProxy(
        new DatabaseAddressFinder("java:comp/env/jdbc/MyDataSourceRef"),
        AddressFinder.class);
  4. 从另一个线程中,使用上下文代理在原始线程的上下文中调用方法。
    Address myAddress = addressFinder.getAddress(me);

指示主题类型的图标 任务主题



时间戳记图标 最近一次更新时间: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=tasb_cproxies
文件名:tasb_cproxies.html