PDA

View Full Version : How to clone a bean?



jbetancourt
Oct 30th, 2004, 06:33 PM
Was looking at some options I have for reusing an object and was considering cloning an existing object since the new copy differs in one field.

I think I can get around the use of cloning. But, now I'm wondering how object cloning would be done using Spring. getBean either creates a new object or reuses an existing one, right.

I haven't looked at all the object factories yet. Maybe there is something that does this already, of course.

Edward Kenworthy
Oct 31st, 2004, 03:21 AM
Two possible approaches:

create several beans (different ids) of the same class at set their attributes in your beans.xml/applicationcontext.xml.

or make the bean singleton="false" so you get a new instance of the class each time you call getBean(), have Spring set all the common values and your code set the ones that differ.

jbetancourt
Oct 31st, 2004, 04:40 AM
Two possible approaches:

create several beans (different ids) of the same class at set their attributes in your beans.xml/applicationcontext.xml.

or make the bean singleton="false" so you get a new instance of the class each time you call getBean(), have Spring set all the common values and your code set the ones that differ.

I too thought that the second option was viable. Since one reason for using clone is to avoid reconstruction of expensive contained objects, these objects can just be referenced as singleton beans in Spring.

Would the framework friction add more cost and thus eliminate any advantage of using clone? BTW, in a simple test, clone did not prove faster then 'new', probably a bad test.

Another option is storing a factory in the context; this factory would have, in addition to the create methods, a clone method that takes run-time parameters.