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:
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 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(); } }
ClassB is also prototype as I hold the reference of ClassA in it..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 } }
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.Code:public class Client { @Autowired private IClassA classA; public void callClientCode () { classA.setAccount("12345678"); classA.doComplexLogic(); } }
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 ?


Reply With Quote
