代码中有一些设计模式吗?

3
我查看了Spring 3.05源代码,并找到了这个类。
public class ContextLoaderListener extends ContextLoader implements ServletContextListener{
    private ContextLoader contextLoader;

    public void contextInitialized(ServletContextEvent event){
       if(this.contextLoader  == null){
          this.contextLoader = this;
       }
       this.contextLoader.initWebApplicationContext(event.getServletContext());
   }

}

为什么使用contextLoader字段,而不直接使用this.initWebApplicationContext(event.getServletContext())?

这种用法有什么好处吗?


好问题。我没有看到任何好处。但是查看源代码历史,在Spring 2.5.6中,我发现ContextLoaderListener不是ContextLoader的子类,并且它有一个方法createContextLoader()(现在已弃用),该方法返回ContextLoader的实例。在当前状态下,它扩展了ContextLoader,因此引用了this。请参见此链接 - Sundeep
这个问题似乎不适合在此处讨论,应该发到 Code Review Stack Exchange 网站上。 - josephus
1个回答

3

我不知道你从哪里找到那段代码,但是Spring 3.0.5的ContextLoaderListener源代码(例如这里)拥有以下内容:

public void contextInitialized(ServletContextEvent event) {
    this.contextLoader = createContextLoader();
    if (this.contextLoader == null) {
        this.contextLoader = this;
    }
    this.contextLoader.initWebApplicationContext(event.getServletContext());
}

你忘记了方法的第一行!

createContextLoader()已被弃用,最终将被移除。 - Sundeep
1
@Sundeep - OP特别询问3.0.5版本,该版本中仍然存在该代码(尽管已弃用)。 - Ted Hopp
糟糕,我的错。该方法返回 null,因为它已被弃用。 - Sundeep
2
@Sundeep - 在后续版本中,整个方法体是一行代码:initWebApplicationContext(event.getServletContext()); - Ted Hopp
现在明白了,谢谢! - Sundeep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接