Search code examples
javaguice

How to provide parameter to Google's Guice Provider?


Lets assume the UI is supposed to pass either 2 or 4 depending on what choice user makes. The backend is using a Provider from Guice to instantiate the valid class. However the 'get' itself does not take in any parameter, however I want to do something like the sameple code below. How can this be accomplished ?

public class VehicleProvider implements Provider<Vehicle> {

    public Vehicles get(int numberOfTyres) {
        /**
         * numberTyres == 2
         *    return new TwoWheelVehicles
         * numberTyres == 4
         *    return new FourWheelVehicles
         */
    }
}

Solution

  • To do the thing most similar to "passing a parameter to a provider", you could define a factory class, for example:

    class VehicleFactory {
      Vehicle build(int numWheels) {
        return new Vehicle(numWheels);
      }
    }
    

    and then inject this factory to the place which needs to create the instances of Vehicle.

    You could consider using Assisted injection to define the bindings for the factory; assisted injection confuses me a lot whenever I use it, so you may want to consider simpler solutions first.

    If you actually only need to create 2- or 4-wheeled vehicles (and not some other arbitrary number), you could give your factory specific methods:

    class VehicleFactory {
      Vehicle buildTwoWheeled() {
        return new Vehicle(2);
      }
    
      Vehicle buildFourWheeled() {
        return new Vehicle(4);
      }
    }
    

    Or you could bind separate instances of the provider:

    public class TwoWheelVehicleProvider implements Provider<Vehicle> { ... }
    public class FourWheelVehicleProvider implements Provider<Vehicle> { ... }
    

    Or, define binding annotations:

    @Provides @TwoWheeled
    Vehicle provideTwoWheeledVehicle() { return new Vehicle(2); }
    
    @Provides @FourWheeled
    Vehicle provideFourWheeledVehicle() { return new Vehicle(4); }