Optional Injection in Guice

I need to enter a field only if it is available in the current area, and null otherwise. For instance:

public class Thinger implements Provider<SomeSuch> { public @Inject(optional=true) HttpServletRequest request; public SomeSuch get() { return request == null ? new WhosIt() : WhatsIt(); } } 

However, if the HttpServletRequest is attached (this is it), but not in scope, I get a ProvisioningException. I was able to find an elegant way to do this, so I stepped back to do something like.

 HttpServletRequest request = null; try { request = injector.getInstance(HttpServletRequest.class); } catch(ProvisioningException e) {} 

Which just feels all kinds of mistakes. Is there any way to do this?

+4
source share
1 answer

What exactly defines your class for accessibility? HttpServletRequest somehow contradicts me, since the lack of a request in a service with no request for a request sounds like an error to me.

One idea would be to write a custom provider for the holder with only the get / set method. In the provider, you can run checks, regardless of whether your Item is available in the current area, it always returns the holder of the type that you need, but may be empty / zero depending on what item is available. Since you always return the holder, the injector should be in order. You just need to check the null value in the component you are inserting it into.

Hope this helps.

+3
source

Source: https://habr.com/ru/post/1335181/


All Articles