Home > Mobile >  Java Spring: Autowire an implementation of an interface based on the value of a property in the same
Java Spring: Autowire an implementation of an interface based on the value of a property in the same

Time:09-29

I have 2 classes

public class Vehicle {

     // Some irrelevant fields, not shown here.

  
     @ManyToOne
     @JoinColumn(name = "VehicleTypeId")
     private VehicleType vehicleType;

     // 'PricingStrategy' is an interface with 2 implementations (see below)
     // This field should be autowired based on the value of this.vehicleType.GetVehicleType()
     private PricingStrategy pricingStrategy;

}



public class VehicleType {

    // Some irrelevant fields, not shown here.

    // Vehicle type has can have 4 different values.
    @Getter @Setter
    private string vehicleType;


}

PricingStrategy is an interface with 1 method and 2 implementations:

public interface PricingStrategy {
     double calculatePrice();
}

public class PricingStrategyA implements PricingStrategy {
    public double calculatePrice() {
      // Implementation is left out.
      return 0.5;
    }
}

public class PricingStrategyB implements PricingStrategy {
    public double calculatePrice() {
      // Implementation is left out.
      return 0.75;
    }
}

I want to use dependency injection to autowire either PricingStrategyA or PricingStrategyB into the Vehicle class based on the value of vehicleType in the class VehicleType.

In pseudocode:

 // Somewhere in the class 'Vehicle'.
if (vehicleType.getVehicleType() == 'X' OR 'Y' then use PricingStrategyA else use PricingStrategyB

Is this at all possible?

CodePudding user response:

You could create a Factory, returning the correct implementation:

public PricingStrategy getPricingStrategy(char input) {
  return (input == 'X' || input == 'Y') 
      ? (PricingStrategyA)applicationContext.getBean("pricingStrategyA") 
      : (PricingStrategyB)applicationContext.getBean("pricingStrategyB");
}
  • Related