Announcement Announcement Module
Collapse
No announcement yet.
Prototype inside a Singleton reference - Proxy Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Prototype inside a Singleton reference - Proxy

    I am currently working a web application which uses spring.. I have come across the famous problem of Prototype reference inside a Singleton.

    Let me explain with an example:

    Code:
    @Component
        @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
        public class ClassA implements IClassA{
    
        @Autowired
        private ITestB testB;
        private ObjectA objectA;
        private ObjectB objectB;
        private ObjectC objectC;
        private ObjectD objectD;
    
        private String account;
    
        public void setAccount(String account) {
        this.account = account;
        testInterface.setClassA(this);
        }
    
         public String getAccount() {
         return account;
         }
    
       public void doComplexLogic() {
        testB.populateBalance();
       }
    }
    I need ClassA to be a prototype as I create and hold references of ObjectA,B,C,D in this class which will be used for manipulations later on..

    Code:
    @Component
            @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS, value = "prototype")
      public class ClassB implements ITestB {
    private IClassA classA; 
    public void setClassA(IClassA classA) {
    this.classA = classA;
    }
    public void populateBalance() {
     String accountId = classA.getAccount();
     //Complex logic
    }
    }
    ClassB is also prototype as I hold the reference of ClassA in it..

    Code:
    public class Client {
    
    @Autowired
    private IClassA classA;
    
    public void callClientCode () {
    classA.setAccount("12345678");
    classA.doComplexLogic();
    }
    }
    In the above code, when client invokes setAccount & doComplexLogic methods, each time a new instance of Client is created as classA is referred in both places.

    Since, a new instance of the object gets created everytime i refer the prototype class, I am unable to set a value and get the same later on..

    If you see the above code, setAccount in ClassA sets an account info which will be used across for manipulations in TestClassA..

    How do I achieve this ? Am i doing something wrong here ?
Working...
X