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?