简体   繁体   中英

Does Injector.getInstance() always call a constructor?

I'm debugging a situation where it seems Guice does not call a constructor. It successfully executes Foo foo = injector.getInstance(Foo.class) ( Foo is a concrete class), and the debugger shows foo is not null after this statement ... yet the constructor is not called.

All of foo 's fields are null, and a statement I put in the constructor that creates a file on disk is not called.

There are no other constructors, and Foo is not a singleton - just bound normally. This is happening when the application starts. The constructor for Foo is never run at all - the file I mentioned it tries to create in the constructor is never created, which means the constructor code never ran.

I'm running inside Play Framework's bootstrap class, trying to wire Guice to work with it after having some problems with Play's Guice Module .

Edit - I just found that I had a missing @Inject on the constructor (it had parameters, and @Inject is mandatory on such constructors). But the question is still valid - what actually happened here? Did Guice create the object without running the constructor, or did Play?

No, not at all. Scopes, such as singleton, exist to control when new objects are (and aren't) created. Additionally, something might be bound to an existing instance of an object. For example, if Foo were an enum , getInstance certainly wouldn't be calling a constructor.

As to what actually happened there, I couldn't say. For something that's bound normally (not to a provider or an existing instance, for example), Guice should only create an object if it has an @Inject annotated constructor or has only a single, no-arg constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM