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

Ana*_*666 7 java spring garbage-collection

我是Spring框架的新手.我对Spring中的singleton概念感到困惑,它是垃圾收集.我已经阅读了很多问题和文章来获得我的问题的答案,即Spring Singleton范围是如何被垃圾收集的.我只得到了关于原型范围垃圾收集的答案,但关于单例范围的文章对我来说并不清楚.有人可以提供有关此问题的详细信息.

Jam*_*ENL 7

在Spring,你写的大部分课程都是单身.这意味着只创建了这些类的一个实例.这些类是在Spring容器启动时创建的,并在Spring容器停止时被销毁.

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

我将举例说明使用Spring容器来说明我的意思.这是不是写一个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");
    }
}
Run Code Online (Sandbox Code Playgroud)

以上代码的作用是对Spring说"我想要在容器启动时发现的MyBean实例"(Classpath Scanning).Spring应该已经创建了这个类的(代理)实例,可供您使用.

来自Spring文档

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

由于该bean已缓存在应用程序上下文中,因此在销毁应用程序上下文之前,它永远不会有资格进行垃圾回收.