Announcement Announcement Module
Collapse
No announcement yet.
How to clone a bean? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to clone a bean?

    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.

  • #2
    Re: How to clone a bean?

    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.

    Comment


    • #3
      Re: How to clone a bean?

      Originally posted by Edward Kenworthy
      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.

      Comment

      Working...
      X