struts2源码中广泛出现的ExternalContext和InternalContext的用途是什么?
<T> T getInstance( Class<T> type, String name, InternalContext context )
{
    ExternalContext<?> previous = context.getExternalContext();
    Key<T> key = Key.newInstance(type, name);
    context.setExternalContext(ExternalContext.newInstance(null, key, this));
    try {
        InternalFactory o = getFactory(key);
        if (o != null) {
            return getFactory(key).create(context);
        } else {
            return null;
        }
    } finally {
        context.setExternalContext(previous);
    }
}
这段代码是ContainerImpl中获取对象实例的方法. 其中InternalContext和ExternalContext很明显是一种策略模式, 提供一种具体策略供getFactory(key).create(context)使用, 但是我仍然不知道他们具体的作用是什么.
InternalContext的源码注释如下:
Internal context. Used to coordinate injections and support circular dependencies.
我直译过来就是"内部容器, 用来协调注入, 并且支持环行依赖"
ExternalContext的源码注释是:
An immutable snapshot of the current context which is safe to expose to client code.
当前上下文的一个不可改变且暴露在在客户端代码下也是安全的快照.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
人生最曼妙的风景,竟是内心的淡定与从容!