简体   繁体   中英

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

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?

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM