开发者

Optional Scoped injection in Guice

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(Http开发者_开发技巧ServletRequest.class);
} catch(ProvisioningException e) {}

Which just feels all manner of wrong. Is there a proper way to do this?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜