user3287019
user3287019

Reputation: 321

Spring Autowire Bean with multiple Interface Implementations, define Implementation in method

I am new to spring and spring boot, so hopefully it is not a silly question.

I have an interface with several implementations. Implementations are annotated with @Component("NameOfImpl").

My goal is to autowire a bean with selected implementation. In a normal case I can do it with @Autowired @Qualifier("NameOfImpl"), but my Problem is I want to select an Implementation in a method like:

public void doSomethingMethod(){ 
      for(String line: configFile){
                String[] values = line.split(";");

                if (values[0].equals("A")) {
                    //here I want to select an bean implementation

                }
                else if (values[0].equals("B")) {
                    //here I want to select another bean implementation

                }
      }
      bean.doSomething();
    }

How can I achieve that? What do you suggest? Thank you!

Upvotes: 3

Views: 4263

Answers (2)

Dinuka Hettiarachchi
Dinuka Hettiarachchi

Reputation: 77

This is also working

public interface Example {

}

@Component("foo")
public class FooExample implements Example {

}

@Component("bar")
public class BarExample implements Example {

}

You can simply Auto wire them

@Component
public class ExampleConsumer {

 @Autowired
    private final Map<String, Example> examples;


}

"foo" -> FooExample instance "bar" -> BarExample instance

Upvotes: 0

Andy Wilkinson
Andy Wilkinson

Reputation: 116061

You can ask Spring to inject a Map of beans. The keys in the map will be the beans' names.

If you have an interface named Example

public interface Example {

}

And two implementations:

@Component("foo")
public class FooExample implements Example {

}

@Component("bar")
public class BarExample implements Example {

}

You can have a map of Example beans injected:

@Component
public class ExampleConsumer {

    private final Map<String, Example> examples;

    @Autowired
    public ExampleConsumer(Map<String, Example> examples) {
        this.examples = examples;
    }
}

In this case the map will contain two entries:

  • "foo" -> FooExample instance
  • "bar" -> BarExample instance

Upvotes: 11

Related Questions