Guice 中可选的范围注入
仅当字段在当前范围内可用时,我才需要注入该字段,否则为 null。例如:
public class Thinger implements Provider<SomeSuch> {
public @Inject(optional=true) HttpServletRequest request;
public SomeSuch get() {
return request == null ? new WhosIt() : WhatsIt();
}
}
但是,如果 HttpServletRequest 已绑定(确实如此)但不在范围内,我会收到一个 ProvisioningException。我已经能够找到一种优雅的方式来做到这一点,所以我被降级做类似的事情。
HttpServletRequest request = null;
try {
request = injector.getInstance(HttpServletRequest.class);
} catch(ProvisioningException e) {}
这感觉完全不对劲。有没有正确的方法来做到这一点?
I need to inject a field only if it is available in the current scope, and null otherwise. For example:
public class Thinger implements Provider<SomeSuch> {
public @Inject(optional=true) HttpServletRequest request;
public SomeSuch get() {
return request == null ? new WhosIt() : WhatsIt();
}
}
However, if HttpServletRequest is bound (which it is) but not in scope, I get a ProvisioningException. I have been able to find an elegant way to do this so I am relegated to do something like.
HttpServletRequest request = null;
try {
request = injector.getInstance(HttpServletRequest.class);
} catch(ProvisioningException e) {}
Which just feels all manner of wrong. Is there a proper way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
究竟是什么决定了您的课程是否可用? HttpServletRequest 在某种程度上对我来说是违反直觉的,因为在非请求范围的服务中没有请求对我来说听起来像是一个错误。
一个想法(通常)是为 Holder 编写一个自定义 Provider,仅使用 get/set 方法。在提供程序中,您可以运行检查,无论您的事物在当前范围内是否可用,它总是返回您需要的类型的 Holder,但它可能为空/空,具体取决于可用的事物。由于您总是返回支架,因此注射器应该没问题。您只需要在要注入的组件中检查 null 即可。
希望这有帮助。
What exactly determines your class to be available? The HttpServletRequest in somehow counterintuitive to me, since not having a request within a non request-scoped service sounds like an error to me.
One idea would (in general) be to write a custom Provider for a Holder with just a get/set method. In the provider you can run the checks, whether or not your Thing is available in the current scope, it always returns a Holder of the type you need, but it might be empty/null depending on the thing being available. Since you always return a Holder the Injector should be fine. You just need to check for null in the component you are injecting this into.
Hope this helps.