Guice 中可选的范围注入

发布于 2024-10-11 09:31:54 字数 605 浏览 7 评论 0原文

仅当字段在当前范围内可用时,我才需要注入该字段,否则为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兮颜 2024-10-18 09:31:54

究竟是什么决定了您的课程是否可用? 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文