Clarify a situation with a cleaning Spring Prototype-beans from memory

萝らか妹 提交于 2019-12-05 07:44:35

Once you create a prototype bean; you are responsible for its lifecycle.

Once you have no reference to that bean it is gone. The only real differences between a prototype bean and a scoped bean is how it is managed by the container.

In a unit test you would not rely on the container to give you these beans you would simply new them yourself.

So to really answer your question, if you allow the prototype object to be dereferenced by your application, the jvm's default behavior will eliminate these beans.

 public class Example {

    @Scope("prototype")
    public static class SomePrototypeBean{

    }

    @Singleton
    public static class MySingleton{

        @Bean
        private SomePrototypeBean somePrototypeBean;

    }

    public static void main(String[] args){
       // context creation code goes here

       // singleton is created, a prototype injected
       context.getBean(MySingleton.class);
       // NOTE: the prototype injected will last for as long as MySingleton has reference
       // my singleton will exist for as long as the context has reference

       doStuff(context);
       //prototype bean created in the method above will be GCed
    }

    public static void doStuff(Context context){
        context.getBean(MyPrototypeBean.class);
        //since we literally are doing nothing with this bean, it will be 
        // marked for garbage collection
    }

}  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!