Regarding the scope and garbage collection in Spring bean container

后端 未结 2 1627
轻奢々
轻奢々 2021-02-07 07:16

I am new to Spring and I am currently using it in one of my projects. I learned that the Spring container holds all the beans and the scope of all the beans is \"singleton

相关标签:
2条回答
  • 2021-02-07 07:39

    From Spring documentation (3.5.2 The prototype scope):

    In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.

    Simply put - once you create and obtain a reference to prototype scoped bean, it is the only reference existing in the JVM. Once this references gets out of scope, the object will be garbage collected:

    void bar() {
      Object foo = ctx.getBean("foo")
    }
    

    The moment you leave bar() method there aren't any other references to new instance of foo, which means it is eligible for garbage collection. The consequence of this model is:

    Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

    0 讨论(0)
  • 2021-02-07 07:48

    The container doesn't keep a reference to instantiated beans, the code that's using them does.

    If nothing else references the bean (roughly), it's eligible for GC.

    0 讨论(0)
提交回复
热议问题