java - 关于 Spring bean 容器中的作用域和垃圾回收

标签 java spring garbage-collection

我是 Spring 新手,目前正在我的一个项目中使用它。我了解到 Spring 容器包含所有 bean,所有 bean 的范围默认为 "singleton"。我可以在 application-context.xml 文件中或使用注释 @Scope 更改范围。 我进一步了解到,如果一个类具有 "prototype" 范围,则 Spring 容器将在需要时实例化该类的新对象。

我不明白的是:垃圾收集是如何处理的。如果不再需要创建的对象,它们是否会被垃圾回收,或者它们仍会保留在容器中。显然,我不希望创建和保留很多对象以保持低内存使用率。

最佳答案

来自 Spring 文档 (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.

简单地说 - 一旦你创建并获得了对 prototype 范围 bean 的引用,它就是 JVM 中存在的唯一引用。一旦此引用超出范围,该对象将被垃圾回收:

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

离开 bar() 方法的那一刻,没有任何其他对 foo 新实例的引用,这意味着它可以进行垃圾回收。这个模型的结果是:

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.

关于java - 关于 Spring bean 容器中的作用域和垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419073/

相关文章:

java - CharSequence equals() 不能正常工作

java - 关于@PostConstruct 的问题

java - 如何在 Controller 中映射两个不同的url : one url with param and the same without the param?

Spring Data,JPA @OneToMany Lazy fetch 在 Spring Boot 中不起作用

wpf - 附加依赖对象被销毁\断开连接时的垃圾收集

java - OAuth2 全局方法安全性

Java:如何测试调用 System.exit() 的方法?

java - 运行简单的mapreduce作业时出现错误 "java.lang.OutOfMemoryError: Java heap space"

memory-management - 为什么要在网络应用程序中进行垃圾收集?

java - Getters 和 Setters、线程和 Java