Spring Prototype scoped bean in a singleton

后端 未结 5 1388
你的背包
你的背包 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:45

    Singleton bean is created only once so the prototype bean which is injected also will be created once at the instantiation of singleton bean.The same instance of prototype bean will be used for every request.

    If new instance of prototype bean will be created for each request at runtime ,the below method Injection can be used

    Example

    public class Singleton {
        private Prototype prototype;
    
        public Singleton(Prototype prototype) {
            this.prototype = prototype;
        }
    
        public void doSomething() {
             prototype.foo();
        }
    
        public void doSomethingElse() {
            prototype.bar();
        }
    }
    
    public abstract class Singleton {
        protected abstract Prototype createPrototype();
    
        public void doSomething() {
            createPrototype().foo();
        }
    
        public void doSomethingElse() {
            createPrototype().bar();
        }
    }
    
    
    
    
       
    
    

提交回复
热议问题