Announcement Announcement Module
Collapse
No announcement yet.
How to dynamically inject different implementation for the same interface using IoC? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to dynamically inject different implementation for the same interface using IoC?

    Hello,

    Here is what I want to do

    I have one interface and two implementations for this interface

    Interface definition:

    Public interface DoSomething {}

    Two implementations:

    Public ImplementationOne implements DoSomething{}
    Public ImplementationTwo implements DoSomething{}

    Then inside another class, I want to get a different implementaion (either ImplementationOne or ImplementationTwo) based on the condition, how can I do that using Spring IoC container?

    If we do not use Spring IoC, we could do something as below...

    Public ServiceManager {
    Private DoSomething doSomething = null;
    Public void do() {
    If (condition1) {
    doSomething = new ImplementationOne();
    } else {
    doSomething = new ImplementationTwo();
    }
    }
    }
    or put the class name in the property file, then use Class.forName()...

    Condition1.implementation.class=com.mycompany.Impl ementationOne
    Condition2.implementation.class=com.mycompany. ImplementationTwo

    Thanks

  • #2
    You could inject both of them into ServiceManager:
    Code:
    private DoSomething doSomethingOne;
    private DoSomething doSomethingTwo;
    
    private DoSomething doSomething;
    
    public void setDoSomethingOne(final DoSomething doSomethingOne) {
        this.doSomethingOne = doSomethingOne;
    }
    
    public void setDoSomethingTwo(final DoSomething doSomethingTwo) {
        this.doSomethingTwo = doSomethingTwo;
    }
    
    public void do() {
        if (condition1) {
            doSomething = doSomethingOne;
        } else {
            doSomething = doSomethingTwo;
        }
    }

    Comment


    • #3
      lol, because I am quite new to Spring, never thought I can do this, very interesting..., thanks a lot

      Comment


      • #4
        Duplicate.

        Comment

        Working...
        X