Explicitly refuse injection

29 views
Skip to first unread message

Geoff Groos

unread,
Jun 20, 2014, 1:05:00 AM6/20/14
to google...@googlegroups.com
Hey guys,

I've personally been burned a couple times now by adding a dependency that I really shouldn't have, but because that dependent had a default constructor, Guice let me get away with it, leaving me to sort out the rather bizarre consequences. I didnt really mind since I'd learned my lesson, but as the project goes forward configuring guice is becoming an increasingly common dev task, so I'd like to shield me and my team from this bug in the future, since, in our configuration, it's fairly easy to run into.

What I'd like is something along these lines:

public class ModelObjectThatHasSensitiveLifeCycle{

    @NeverInject
    public ModelObjectThatHasSensitiveLifeCycle(){
    }
}


The idea being that, upon seeing the @NeverInject constructor, guice will refuse to instance it, giving an error message to the effect of "bind a custom provider or supply an existing instance".

I suppose I could use static factory that just hits a private default constructor, but I dont really like imposing a convention on our devs because a library wont cooperate, I'd rather have an annotation that speaks directly to the problem. Further conventions aren't as strong as red characters in std:err.

I've tried using your the introspection SPI to do what I'm looking for, but I'm a little lost on your domains terminology, so I think I'm throwing in the towel.

Heres a little bit of code I'd like to be able to run if I could manage it:
https://gist.github.com/Groostav/df57208770a6bd6a1c3d

cheers,

-Geoff

Christian Gruber

unread,
Jun 20, 2014, 1:12:27 AM6/20/14
to google...@googlegroups.com
As of the 4.0-betas you can do

binder().requireAtInjectOnConstructors();

This will cause Guice to refuse to JIT bind default constructors. It
will only notice constructors marked with @Inject. I think this is a
more workable solution, as it doesn't require that you modify code to
have Guice ignore it.

cheers,
Christian.
> --
> You received this message because you are subscribed to the Google
> Groups "google-guice" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to google-guice...@googlegroups.com.
> To post to this group, send email to google...@googlegroups.com.
> Visit this group at http://groups.google.com/group/google-guice.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/google-guice/23c467a1-a256-434a-bc6e-c7fcd9c37677%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.


Christian Gruber :: Google, Inc. :: Java Core Libraries :: Dependency
Injection
email: cgr...@google.com :::: mobile: +1 (646) 807-9839
Reply all
Reply to author
Forward
0 new messages