Optional dependencies and default values

37 views
Skip to first unread message

Edgar Espina

unread,
Jun 27, 2014, 4:02:11 PM6/27/14
to google...@googlegroups.com
Hi,

 I'm using Guice to inject HTTP Request parameters (I'm not using guice-servlet) and I will like to do things like:

public class Command {
  public Command(@Named("name") String name) {
  }
}

 Here "name" is an HTTP parameter and I'm able to bind it when present.

 The problem (of course) is when that parameter isn't present or sent and want to have a default value for it.

 I know isn't possible to inject something without a binding and it's OK. So what I'm asking here is feedback on how to deal with this? and/or an alternate solution?

Thanks,

edgar

Tim Boudreau

unread,
Jun 29, 2014, 5:18:38 AM6/29/14
to google...@googlegroups.com
I think @Named is not a good fit for that, for precisely the reasons you specify.  Guice has to know the names of things that will be injected ahead of time.  There are ways I can think of that you could torture Guice into doing what you're after (if you really want I can describe them), but there's no getting around telling Guice the names of every parameter you're ever going to want to consume;  then you could do a custom scope with Providers for all of them.

I did something that achieves the same end in my Acteur web framework,which sits on top of Guice+Netty:

Basically you create an interface with one method for each parameter that might be present;  the framework will implement it as a dynamic proxy and make it available for injection.  That gets you something naturally null-tolerant and with at least minimal validation that number parameters are actually numbers and so forth.

You might try something like that - it's both a more OOP-like approach, and avoids weirdness like having to make sure there are no name clashes between URL parameters and anything else you're using @Named for.

-Tim

Tim Boudreau

unread,
Jun 29, 2014, 5:19:32 AM6/29/14
to google...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages