Spring Prototype scoped bean in a singleton

后端 未结 5 1391
你的背包
你的背包 2020-11-29 23:50

I am trying to inject a prototype bean in a singleton bean such that every new call to a singleton bean method has a new instance of the prototype

5条回答
  •  我在风中等你
    2020-11-30 00:34

    From Spring documentation:

    You do not need to use the in conjunction with beans that are scoped as singletons or prototypes. If you try to create a scoped proxy for a singleton bean, the BeanCreationException is raised.

    It seems the documentation has changed a bit for version 3.2 documentation where you can find this sentence:

    You do not need to use the in conjunction with beans that are scoped as singletons or prototypes.

    It seems that its not expected you use a proxied prototype bean, as each time it is requested to the BeanFactory it will create a new instance of it.


    In order to have a kind of factory for your prototype bean you could use an ObjectFactory as follows:

    @Component
    public class SingletonBean {
    
        @Autowired
        private ObjectFactory prototypeFactory;
    
        public void doSomething() {
            PrototypeBean prototypeBean = prototypeFactory.getObject();
            prototypeBean.setX(1);
            prototypeBean.display();
        }
    }
    

    and your prototype bean would be declared as follows:

    @Component 
    @Scope(value="prototype")
    public class PrototypeBean {
        // ...
    }
    

提交回复
热议问题