【发布时间】:2018-10-01 18:28:58
【问题描述】:
我有必要在运行时提供正确的 Bean 实现。
通用接口:
public interface MyInterface { ... }
实现:
@Named("one")
class MyInterfaceImpl1 implements MyInterface { ... }
@Named("two")
class MyInterfaceImpl2 implements MyInterface { ... }
@Named("three")
class MyInterfaceImpl3 implements MyInterface { ... }
注意这些类是包私有的。
然后我写了一个@Produces方法:
@Produces
@Singleton
MyInterface getMyInterface(
final Instance<MyInterface> myInterfaceImplementations,
final Configuration configuration) {
// Might be one, two or three.
final String parameter = configuration.getString("value");
return myInterfaceImplementations.select(new NamedLiteral(parameter)).get();
}
这是正确的方法,还是有更好的解决方案?
【问题讨论】:
-
您的解决方案似乎很好,除了 2 个细节:(1)您确定
@Singleton是否符合您的预期?我会使用@ApplicationScoped。 (2) 如果生成的 bean 确实打算成为单例,那么您正在无缘无故地创建 N-1 个 bean(除非在其他地方按名称使用)。这可能严重或不严重,取决于未使用的 bean 的“重量”程度。 -
@NikosParaskevopoulos 嗨!是的,我真的不需要代理对象,我只需要容器为每个 JVM 实例化一次。对于(2)点,我想我没有明白,你能详细说明一下吗?谢谢!嗯,你是说每个注入点都会调用 Producer 方法,即使它被标记为 Singleton?