0
  1. Spring 何时优雅地卸载 Spring 容器 (XMLBeanFactory)?
  2. 当应用程序正在运行但 BeanFactory 的唯一处理程序超出范围时会发生什么?
  3. 加载 Spring 容器的理想方式是什么?是在做handler = new BeanFactory()正确的方法吗?


更新:
当容器超出范围时,我们确实希望调用 close() 方法,这反过来会释放所有持有的资源。但这不会发生!我遇到了一个案例,我的 spring 容器超出了范围,但内存仍然满了(OutOfMemory 错误)。原因是我的 Spring 容器创建的 SessionFactory 对象从来没有被垃圾收集,因为它们被创建为静态的。这意味着close()->destroy()当容器超出范围时从未调用过。让我相信 Spring 本身存在泄漏问题。

4

2 回答 2

3
  1. This depends on how you're instantiating it. I a webapp, this is typically done at context shutdown. On the command line, you have to specifically close the context (via the "close" method on "AbstractApplicationContext"
  2. Same as anything else that falls out of scope. Not sure if the "close" method is part of the finalizer phase or not. I would hope the finalizer would trigger the destroy phase.
  3. As someone else said, don't use BeanFactory directly. Create an ApplicationContext. The most common way for web apps is the ContextLoaderListener, and for command line programs would be ClassPathXmlApplicationContext.

// Keep a specific type, so we can call the "close" method later since it's // not part of the ApplicationContext interface itself. ClasspathXmlApplicationContext context = new ClasspathXmlApplicationContext(new String[] { "applicationContext.xml });

and then later on you close it:

context.close();

For webapps:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>
于 2012-05-29T16:59:27.470 回答
0

BeanFactory 是 Spring 中古老的做事方式。实例化 Spring 上下文的更现代的方法是通过 ApplicationContext 接口。供参考,请阅读

4.2.2 实例化一个容器

如果您打算在 Web 应用程序中使用 Spring,另请阅读

4.14.4 Web 应用程序的便捷 ApplicationContext 实例化

于 2012-05-29T15:15:29.973 回答