Search code examples
javaspringinheritancesoalate-binding

Inheritance (Late Binding) via Dependency Injection in Java


I am using Spring DI to wire my components and I came across this issue.

I have a BaseService class which has multiple implementations. And the layer above it, has a builder which calls the service to get data to populate POJOs. Service implementation I need to call (ServiceA,ServiceB) changes according to the type of POJO I need to build.

In such case, how can I autowire the service, as it requires late binding the service. How can I tackle this kind of scenario? (Example in Spring DI would really help)

Builder calling Services

I read similar questions but could not find the answer. And I read that SOA patterns such as Service Host provide different solutions to exact use case.

Please help. Thanks


Solution

  • You can use ServiceLocatorFactoryBean. In your case you would do something like this:

    public interface BaseServiceLocator {
    
       BaseService lookup(String qualifier); //use whatever qualifier type makes sense here
    }
    
    <bean id="serviceLocatorFactoryBean"
        class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean">
        <property name="serviceLocatorInterface"
                  value="your.package.BaseServiceLocator" />
    </bean>
    

    Then your builder would look something like this:

    public class Builder {
    
      @Autowired
      private BaseServiceLocator baseServiceLocator;
    
      @Override
      public YourReturnType businessMethod() {
          SomeData data = getData();
          BaseService baseService = baseServiceLocator(data.getType()); //here I am assuming that getType() is a String
    
          //whatever
      }