问题描述
我是Spring框架的新手。我一直对Spring中单例的概念感到困惑,它是垃圾收集。我已经阅读了很多问题和文章,以获得我的问题的答案: Spring Singleton范围如何收集垃圾。我只能得到关于原型范围垃圾收集的答案,但关于单例范围的文章并不清楚。有人可以提供关于此问题的详细信息。
I am new to Spring framework. I have been confused about the concept of singleton in Spring and it's garbage collection. I have read many questions and articles to get the answer to my question that how Spring Singleton scope is garbage collected. I only got the answers about prototype scope garbage collection, but the articles regarding singleton scope were not clear to me. Could someone give the details on this issue.
推荐答案
在Spring中,大多数类都是单例。这意味着只创建了这些类的一个实例。这些类在Spring容器启动时创建,并在Spring容器停止时被销毁。
In Spring, most of the classes you write will be Singletons. This means that there is only ever one instance of these classes created. These classes are created when the Spring container starts and are destroyed when the Spring container stops.
Spring单例对象不同于简单Java对象的原因是容器保持对它们的引用,并且它们可以随时在代码中的任何地方使用。
The reason that Spring singleton objects are different from simple Java objects, is that the container maintains a reference to them, and they are able to be used anywhere in your code at any time.
我将给你一个使用Spring容器的例子来说明我的意思是。这是 NOT 在编写Spring应用程序时通常应该这样做,这只是一个例子。
I'll give you an example using the Spring container to illustrate what I mean. This is NOT how you should do this normally when writing a Spring app, this is just an example.
@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");
}
}
上面的代码对SpringI需要在容器启动时发现的MyBean实例()。 Spring应该有一个(代理)这个类的实例,已经创建并可供您使用。
What the above code does is say to Spring "I want the instance of MyBean that you have discovered when the container started" (Classpath Scanning). Spring should have a (proxy) instance of this class already created and available for your use.
从
因为该bean已被缓存在应用程序上下文中,所以在应用程序上下文被销毁之前,它永远不会被垃圾收集。
Because that bean has been cached inside the application context, it is never eligible for garbage collection until the application context is destroyed.
这篇关于Spring Singleton Scope如何收集垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!