包含单例 bean 的原型 bean 在使用后会被垃圾回收吗?

Will a prototype bean which contains a singleton bean be garbage collected once it is used?

@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 class 要求 Spring 创建它在 [=13= 中使用的原型 bean (ClassA) 的实例] 方法。现在根据 Spring 文档:

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes-prototype

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

如果ClassA实例没有在其他地方使用,它将有资格进行GC。当然由于ClassB是单例,由[=26=管理],因此不会被收集。 classB 还活着的事实并不代表 classA 需要收集。

顺便说一句,你的评论有点不对:

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

您混淆了范围和可达性。这么想,如果那个评论后面有more代码(但是没有用classA)还是可以在before[=24] =] 方法结束。