一旦使用了包含单例bean的原型bean,它会被垃圾收集吗


@Component
class ClassB {
//Singleton class which is being used in classA
public void doSomething() {
System.out.println("did something");
}
}
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ClassA {
//Prototype class which is being used in Main class
@Autowired
ClassB classb;
public void methodA() {
//do something
classb.doSomething();
}
}

@Component
class Main {

@Autowired
ApplicationContext applicationContext;
public void createAndUseClassA() {
//Spring would create a new instance of classA
var classA = applicationContext.getBean(ClassA.class);  
//used class A
classA.methodA();
//after this method ends there would be no reference of classA
}
}

在上面的例子中,Main类要求Spring创建一个原型bean(ClassA(的实例,它在createAndUseClassA()方法中使用该实例。现在根据Spring文档:

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-工厂瞄准镜原型

Spring在创建后不保留对原型bean的任何引用,但Spring在Spring上下文中保留了对singleton bean的引用。因此,在这种情况下,方法createAndUseClassA()完成后,将不会引用classA引用的对象,但Spring上下文将引用对象ClassA内部的ClassB。我的问题是,这会阻止GC在执行createAndUseClassA()之后收集ClassA的实例吗?

如果ClassA实例没有在其他地方使用,它将有资格进行GC。当然,由于ClassB是一个单例,并且由Spring管理,因此不会收集它。CCD_ 12是活的这一事实并不存在要收集的CCD_。

顺便说一句,你的评论有点偏离:

//after this method ends there would be no reference of classA

你混淆了范围和可达性。这样想吧,如果在该注释之后还有更多代码(但它不使用classA(,那么在方法结束之前,它仍然可以被收集

最新更新