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

  • Need to get new instance of a class everytime

    Hello,

    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.

    TIA
    Rob

  • #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.

    http://static.springframework.org/sp...ctoryBean.html

    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:

    http://static.springframework.org/sp...thod-injection

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

    http://blog.springframework.com/rod/?p=1

    Cheers
    Rick 'Scottorum malleus' Evans

    Comment


    • #3
      Hi Rick,

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

      Cheers
      Rob

      Comment


      • #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.

        Code:
        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();
                 pie.eat();
             }
        }
        
        <bean id="pieFactory" class="DefaultPieFactory">
           <property name="taste" value="appel"/>
        </bean>
        
        <bean id="pieEater" class="PieEater">
            <property name="pieFactory" ref="pieFactory"/>
        </bean>
        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.

        Comment

        Working...
        X