Spring Singleton Scope 垃圾是如何收集的?

2024-01-11

我是 Spring 框架的新手。我一直对 Spring 中单例的概念及其垃圾收集感到困惑。我读了很多问题和文章来得到我的问题的答案Spring Singleton 范围如何进行垃圾收集。我只得到了有关原型范围垃圾收集的答案,但有关单例范围的文章对我来说并不清楚。有人可以提供有关此问题的详细信息吗?


在 Spring 中,您编写的大多数类都是单例类。这意味着这些类只会创建一个实例。这些类在 Spring 容器启动时创建,并在 Spring 容器停止时销毁。

Spring 单例对象与简单 Java 对象不同的原因是容器维护对它们的引用,并且它们可以随时在代码中的任何位置使用。

我将给您一个使用 Spring 容器的示例来说明我的意思。这是NOT在编写 Spring 应用程序时通常应该如何执行此操作,这只是一个示例。

@Component
public class ExampleClass implements ApplicationContextAware {
    /* 
     * The ApplicationContextAware interface is a special interface that allows 
     * a class to hook into Spring's Application Context. It should not be used all
     * over the place, because Spring provides better ways to get at your beans
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        MyBean bean = applicationContext.getBean("MyBean");
    }
}

上面的代码的作用是对 Spring 说“我想要容器启动时你发现的 MyBean 实例”(类路径扫描 http://docs.spring.io/spring/docs/3.0.0.RC2/spring-framework-reference/html/ch03s10.html?ref=driverlayer.com/web)。 Spring 应该已经创建了此类的(代理)实例并可供您使用。

来自Spring文档 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-prototype

Spring IoC 容器只创建该 bean 定义所定义的对象的一个​​实例。该单个实例存储在此类单例 bean 的缓存中,并且该命名 bean 的所有后续请求和引用都会返回缓存的对象。

因为该 bean 已缓存在应用程序上下文中,所以在应用程序上下文被销毁之前,它永远不符合垃圾回收条件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Singleton Scope 垃圾是如何收集的? 的相关文章

随机推荐