Announcement Announcement Module
No announcement yet.
Need to get new instance of a class everytime Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Need to get new instance of a class everytime


    in a class I need to get a new instance of another class. Let's say in Class A I need to have an Instance of Class B. Now I want to get a new instance of Class B. Because Class B is injected into Class A via DI I always get the same instance. How can I get a new instance of my class and keep DI?

    I really appreciate any information.


  • #2
    Hi Braveheart

    Lots of options actually.

    ServiceLocatorFactoryBean is the one I prefer. Keeps Spring APIs out of your code, and means you have to code up one interface (Spring supplies the implementation). Lovely jubbly... the Javadocs are quite complete, and spell out how to effect what you want.

    You could also go the quick and dirty way of having Class A implement BeanFactoryAware (or ApplicationContextAware) and pulling a new instance of Class B (a prototype) out. But that ties you architecturally to Spring, and is not really DI, rather Dependency Lookup.

    Another alternative (some camps prefer this approach) is to use Method Injection. This is described in the reference documentation:

    And also in this blog entry from Rod (Johnson).

    Rick 'Scottorum malleus' Evans


    • #3
      Hi Rick,

      thank you very much for pointing out possible solutions. I'll have a look at them now.



      • #4
        If I need a single instance, I inject that instance into the object.

        If I need a new instance everytime, I create a Factory.

        interface PieFactory{
           Pie create();
        class DefaultPieFactory implements PieFactory{
            private String taste;
            Pie create(){
                 return new Pie(taste); 
        class PieEater{
             private PieFactory pieFactory;
             void eat(){
                 Pie pie = pieFactory.create();
        <bean id="pieFactory" class="DefaultPieFactory">
           <property name="taste" value="appel"/>
        <bean id="pieEater" class="PieEater">
            <property name="pieFactory" ref="pieFactory"/>
        This solution doesn't tie you into Spring, it also doesn't change the semantics of the object in a very obscure manner, and it is good design.