【发布时间】:2019-12-05 08:47:12
【问题描述】:
我想在方法上使用 @Produces 注释创建一个 CDI 工厂,以便在外部服务中查找命名的东西并返回(生成)外部服务中该东西的代理以注入其他 bean .从用例的角度来看,通常所有这些依赖项都是必需的;但是有时会发生请求的东西在远程服务中不存在并且应用程序可以对此作出反应。
基本上结构是这样的:
@Singleton public class SomeBean {
@Inject @MyName("required") private Something requiredSomething;
@Inject @MyName("optional") private Instance<Something> optionalSomething;
@PostConstruct void init() {
if (optionalSomething.isUnSatisfied()) {
// act without optional Something in external service
} else {
optionalSomething.get().doWhatIWant(NOW);
}
}
}
@ApplicationScoped
public class SomethingFactory {
@Inject private RemoteSomethingService remoteService;
@Produces
@MyName(value = "")
public Something createRemoteSomething(InjectionPoint injectionPoint) {
MyName name = injectionPoint.getAnnotated().getAnnotation(MyName.class);
Something some = remoteService.lookup(name.value()); // throws an exception if lookup fails
return some;
}
}
这适用于需要在使用某些东西的一侧进行注入的情况:成功的查找注入查找的 Something 实例,而不成功的查找会破坏 bean 引导。然而,在一个不存在的东西的可选注入的情况下,它要么中断,因为Instance.isUnSatisfied() 返回false。如果我让createRemoteSomething() 抛出异常,则在调用optionalSomething.get() 期间会引发此异常;如果我返回 null,同样的调用会导致 NPE。
如何使用 CDI 原语实现这一点?谢谢。
【问题讨论】:
标签: java jakarta-ee cdi