[英]Java Spring: Autowire an implementation of an interface based on the value of a property in the same class
我有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;
}
}
我想使用依赖注入根据 class VehicleType
中vehicleType
的值将PricingStrategyA
或PricingStrategyB
自动装配到Vehicle
class 中。
在伪代码中:
// Somewhere in the class 'Vehicle'.
if (vehicleType.getVehicleType() == 'X' OR 'Y' then use PricingStrategyA else use PricingStrategyB
这是可能吗?
您可以创建一个工厂,返回正确的实现:
public PricingStrategy getPricingStrategy(char input) {
return (input == 'X' || input == 'Y')
? (PricingStrategyA)applicationContext.getBean("pricingStrategyA")
: (PricingStrategyB)applicationContext.getBean("pricingStrategyB");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.