我有 2 節課
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是一個具有 1 個方法和 2 個實作的介面:
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;
}
}
我想根據類中的值使用依賴注入來自動裝配PricingStrategyA或PricingStrategyB進入類。VehiclevehicleTypeVehicleType
在偽代碼中:
// Somewhere in the class 'Vehicle'.
if (vehicleType.getVehicleType() == 'X' OR 'Y' then use PricingStrategyA else use PricingStrategyB
這是可能嗎?
uj5u.com熱心網友回復:
您可以創建一個工廠,回傳正確的實作:
public PricingStrategy getPricingStrategy(char input) {
return (input == 'X' || input == 'Y')
? (PricingStrategyA)applicationContext.getBean("pricingStrategyA")
: (PricingStrategyB)applicationContext.getBean("pricingStrategyB");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/510299.html
標籤:爪哇春天依赖注入自动接线
