WebWork中的IOC

WebWork实际上已经分出了一部分称为XWork,IOC实现在XWork中.

IOC容器实现在包com.opensymphony.xwork.interceptor.component中,为了方便在XWork中扩展,它提供了ComponentManager接口,并提供了缺省实现:DefaultComponentManager.

XWork如何使用组件管理器呢,以WebWork和XWork的合作为例,看看DefaultComponentManager的作用域,在WebWork中组件作用域划分成三类,分别对应了Web应用程序的Application,Session,Request,具体实现在两个侦听器类:ApplicationLifecycleListener,SessionLifecycleListener及一个过滤器类RequestLifecycleFilter,位于com.opensymphony.webwork.lifecycle包中.

ApplicationLifecycleListener细节为:

public class ApplicationLifecycleListener implements ServletContextListener {
    public void contextDestroyed(ServletContextEvent event) {
        ServletContext application = event.getServletContext();
        ComponentManager container = (ComponentManager) application.getAttribute(ComponentManager.COMPONENT_MANAGER_KEY);

        if (container != null) {
            container.dispose();
        }
    }

    初始化XWork组件管理器,从位于类路径中的components.xml文件装入组件配置.
    public void contextInitialized(ServletContextEvent event) {
        ServletContext application = event.getServletContext();
        ComponentManager container = createComponentManager();
        ComponentConfiguration config = loadConfiguration();

        config.configure(container, "application");

        application.setAttribute(ComponentManager.COMPONENT_MANAGER_KEY, container);
        application.setAttribute("ComponentConfiguration", config);
    }
     如果开发者需要子类化这个类,可以通过覆盖这个方法以提供自己的DefaultComponentManager实现.
    protected DefaultComponentManager createComponentManager() {
        return new DefaultComponentManager();
    }

    private ComponentConfiguration loadConfiguration() {
        ComponentConfiguration config = new ComponentConfiguration();
        InputStream configXml = Thread.currentThread().getContextClassLoader().getResourceAsStream("components.xml");

        if (configXml == null) {
            final String message = "Unable to find the file components.xml in the classpath.";
            log.error(message);
            throw new RuntimeException(message);
        }

        try {
            config.loadFromXml(configXml);
        } catch (IOException ioe) {
            log.error(ioe);
            throw new RuntimeException("Unable to load component configuration");
        } catch (SAXException sae) {
            log.error(sae);
            throw new RuntimeException("Unable to load component configuration");
        }

        return config;
    }
}

其它两个类中的ComponentManager对象使用了这个类中配置对象,并没有创建新配置,实际上也无需再建.代码略掉,但可以从XWork源码中查看.

组件生存期

在XWork中采用懒装载,装载点在一个拦截器ComponentInterceptor中:

public class ComponentInterceptor extends AroundInterceptor {
    protected void after(ActionInvocation dispatcher, String result) throws Exception {
    }

    protected void before(ActionInvocation dispatcher) throws Exception {
        ComponentManager container = (ComponentManager) ActionContext.getContext().get(COMPONENT_MANAGER);

        if (container != null) {
            container.initializeObject(dispatcher.getAction());发生在这里
        }
    }
}

组件的使用过程发生在实现ActionInvocation接口的类场景中.与这个场景相关的线程结束后,这个场景中的所有对象将由GC负责清理.

缺省实现的DefaultComponentManager

现在开始分析组件管理器的实现.在这个实现中,使用了反射,Gosling曾在书中使用了面向类型编程介绍了java的反射.

XWork的IOC实现要求受管理的组件要实现一个Enablers:拥有一个setter且只接受一个参数.能够按照被初始化的类以及依赖的资源顺序的初始化,在下面的代码中略去了标准接口的实现.

public class DefaultComponentManager implements ComponentManager, Serializable {
    Map enablers = new HashMap();
    Map enablers2 = new HashMap();
    private DefaultComponentManager fallback;
    private List loadOrder = new ArrayList();
    private Map resourceInstances = new HashMap();
    private Set alreadyLoaded = new HashSet();


    public Object getComponent(Class enablerType) { }

    public void setFallback(ComponentManager fallback) {   }

    public void addEnabler(Class component, Class enablerType) {    }
    把有依赖关系的对象逆序后,释放对象.
    public void dispose() {
        Collections.reverse(loadOrder);

        for (Iterator iterator = loadOrder.iterator(); iterator.hasNext();) {
            Object resource = iterator.next();

            if (resource instanceof Disposable) {
                Disposable disposable = (Disposable) resource;
                disposable.dispose();
            }
        }
    }

    public void initializeObject(Object obj) {
        loadResource(obj, obj.getClass(), this);
    }

    public void registerInstance(Class componentType, Object instance) {
        if (!componentType.isInstance(instance)) {
            throw new IllegalArgumentException("The object " + instance + " is not an instance of " + componentType.getName());
        }
        loadResource(instance, componentType, this);
    }

    public Object getComponentInstance(Class componentType) {

    }
   
    private Map getResourceDependencies(Class resourceClass) {
        List interfaces = new ArrayList();
        找出所有接口
        addAllInterfaces(resourceClass, interfaces);

        Map dependencies = new HashMap();

        for (Iterator iterator = interfaces.iterator(); iterator.hasNext();) {
            Class anInterface = (Class) iterator.next();

            DefaultComponentManager dcm = this;

            while (dcm != null) {
                Class possibleResource = (Class) dcm.enablers.get(anInterface);

                if (possibleResource != null) {
                    dependencies.put(possibleResource, dcm);

                    break;
                }

                dcm = dcm.fallback;
            }
        }

        return dependencies;
    }
   
    private void addAllInterfaces(Class clazz, List allInterfaces) {
        if (clazz == null) {
            return;
        }
        Class[] interfaces = clazz.getInterfaces();
        allInterfaces.addAll(Arrays.asList(interfaces));
        addAllInterfaces(clazz.getSuperclass(), allInterfaces);
    }
    loadResource和setupAndOptionallyCreateResource迭代找出所有依赖资源并初始化。
    private Class loadResource(Object resource, Class clazz, DefaultComponentManager dcm) {
        boolean resourceNotLoaded = !dcm.loadOrder.contains(resource);

        if (resourceNotLoaded) {
            找出所有依赖
            Map resources = getResourceDependencies(clazz);
           
            for (Iterator iterator = resources.entrySet().iterator();
                    iterator.hasNext();) {
                Map.Entry mapEntry = (Map.Entry) iterator.next();
                Class depResource = (Class) mapEntry.getKey();
                DefaultComponentManager newDcm = (DefaultComponentManager) mapEntry.getValue();

                try {
                   
                    ResourceEnablerPair pair = setupAndOptionallyCreateResource(newDcm, depResource);
                   
                    setupResource(resource, pair.enabler, pair.resource);
                } catch (Exception e) {
                    e.printStackTrace();

                    if (log.isDebugEnabled()) {
                        log.debug("Error loading or setting up resource: " + resources.getClass().getName(), e);
                    }
                }
            }

            dcm.alreadyLoaded.add(clazz);
     如果类实现了Initializable接口,则调用init方法。
            if (resource instanceof Initializable) {
                Initializable initializable = (Initializable) resource;
                initializable.init();
            }

            dcm.resourceInstances.put(clazz, resource);
            dcm.loadOrder.add(resource);
        }

        // now return this class's enabler
        Class enabler = (Class) dcm.enablers2.get(clazz);

        return enabler;
    }
    首先开一个资源使能器对,然后检查已经装载的资源中是否存在该资源,没有则从对象工厂中构造一个,并设置到资源使能器对,最后调用
    loadResource继续递归。
   
    private ResourceEnablerPair setupAndOptionallyCreateResource(DefaultComponentManager newDcm, Class depResource) throws Exception {
        ResourceEnablerPair pair = new ResourceEnablerPair();
        Object newResource = newDcm.resourceInstances.get(depResource);

        if (newResource == null) {
            newResource = ObjectFactory.getObjectFactory().buildBean(depResource);
        }

        pair.resource = newResource;

        Class enabler = loadResource(newResource, depResource, newDcm);
        pair.enabler = enabler;

        return pair;
    }
    从这里可以看到,XWork实现只使用了一个方法来设置资源。由此看来这个IOC实现只是配合XWork的工作,相比Spring的IOC容器
    还是相当的简陋。
    private void setupResource(Object resource, Class enabler, Object newResource) {
        if (enabler == null) {
            return;
        }

        try {
            enabler.getMethods()[0].invoke(resource, new Object[] {newResource});
        } catch (Exception e) {
            e.printStackTrace();

            if (log.isDebugEnabled()) {
                log.debug("Error invoking method for resource: " + resource.getClass().getName(), e);
            }
        }
    }

    //~ Inner Classes //

    class ResourceEnablerPair {
        Class enabler;
        Object resource;
    }
}
通过分析,XWork的IOC实现比较简单,单独使用需要考虑很多问题,对于所管理的组件有特定要求,对于追求简单性的Opensymphony来说,这能满足XWork的需要,但要选择一个我们自己使用的IOC容器,选象Spring,PICO等这类方便使用容器为好.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值