Search code examples
javaspringspring-bootdependency-injectionservice-locator

Spring service locator without autowiring it


Having this code:

public class ClassA {

    private InterfaceB interfaceB;

    private int a

    private int b;

    public ClassA(int a, int b) {
       this.a = a;
       this.b = b;
    }
}

There could be several objects of ClassA in my application, created on demand at runtime. But all of them should use the same concrete implementation of InterfaceB class (there are several implementations of InterfaceB but only one is used at runtime depending on the platform used). And there should be only oneInterfaceB object in the application (singleton class).

I can not autowired interfaceB as ClassA objects are created at runtime when a and b constructor parameters are known.

How could I use Spring Framework to implement the service locator pattern here? My plan is to instantiate the service locator in ClassA and use it to get the InterfaceB object.


Solution

  • You could create an additional class that will be creating your ClassA and it will be holding a reference to an interfaceB. For example:

    @Component
    public class ClassAFactory {
    
        @Autowired
        private InterfaceB interfaceB;
    
        public ClassA create(int a, int b) {
           return new ClassA(a, b, interfaceB);
        }
    }
    

    In this case you have to extend the ClassA to pass an interfaceB. Then somewhere in your code you could:

    @Autowired
    private ClassAFactory factory ;
    
    ...
    
    ClassA classA = factory.create(1,1);