我知道我可以将所有与接口匹配的 bean 作为实例注入,然后以编程方式在它们之间进行选择:
@Inject @Any Instance<PaymentProcessor> paymentProcessorSource;
这意味着我必须将选择逻辑放入客户端。
作为替代方案,我可以使用带有 lambda 表达式的词法范围来缓存 ejb 的值吗?在这种情况下,容器是否能够正确管理 ejb 的生命周期,还是要避免这种做法?
例如,将 PaymentProcessorImpl1 e PaymentProcessorImpl2 作为 PaymentProcessor 的两个策略,如下所示:
public class PaymentProcessorProducer {
@Inject
private PaymentProcessorImpl1 paymentProcessorImpl1;
@Inject
private PaymentProcessorImpl2 paymentProcessorImpl2;
@Produces
private Function<String, PaymentProcessor> produce() {
return (strategyValue) -> {
if ("strategy1".equals(strategyValue)) {
return paymentProcessorImpl1;
} else if ("strategy2".equals(strategyValue)) {
return paymentProcessorImpl2;
} else {
throw new IllegalStateException("Tipo non gestito: "
+ strategyValue);
}
};
}
}
然后进入客户端进行类似的操作:
@Inject
Function<String, PaymentProcessor> paymentProcessor;
...
paymentProcessor.apply("strategy1")
不负相思意
相关分类