0

I have multiple provider classes (Provider1 and Provider2), how do I decide what bean I use depending on the input parameter in the Processor class?

public class Processor{
    private Provider provider;

    public void process(String  providerName) throws Exception {
        // What should I do here to invoke either provider1 or provider2 depending on the providerName?
        provider.doOperation();
    }
}

public class Provider1  {
    public void doOperation(Exchange exchange) throws Exception {
        //Code
    }
}

public class Provider2  {
    public void doOperation(Exchange exchange) throws Exception {
        //Code
    }
}
g00glen00b
  • 41,995
  • 13
  • 95
  • 133
user5773508
  • 91
  • 1
  • 1
  • 8

2 Answers2

0

What about somthing like this?

1# into your processor class :

public class Processor{

    private Map<Provider> providers;

    public void process(String providerName) throws Exception {
        Provider provider = providers.get(providerName);
        provider.doOperation();
    }
}

2# in your spring config:

<bean id="provider1" class="xx.yy.zz.Provider1"/>
<bean id="provider2" class="xx.yy.zz.Provider2"/>

<bean id="processor" class="xx.yy.zz.Processor">

  <property name="providers">
    <map>
        <entry key="provider1" value-ref="provider1" />
        <entry key="provider2" value-ref="provider2" />
    </map>
  </property>

</bean>

now for example if you call processor.process("provider1") it will call provider1.doOperation()

Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37
0

This is the case of Factory pattern. You can create a (ProviderFactory) class, register all the providers and get provider based on value, e.g.:

class ProviderFactory(){

    private List<Provider> providers = new ArrayList<>();

    public Provider getProvider(String input){

        if(input.equals("test1")){
            //Find based on criteria
            return provider1;
        }else if(input.equals("test2")){
            //Find based on criteria
            return provider2;
        }
    }

    public void registerProvider(Provider provider){
        providers.add(provider);
    }
}

You can call registerProvider method on application startup and add as many providers as you want. Once that is initialised, you can call getProvider method and return appropriate instance based on some criteria.

Please note that providers doesn't necessarily need to be a list, it can be any data structure. It depends on which structure suits your criteria the best.

Here's documentation/more examples for Factory pattern.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102