1

The Spring lookup method lets you have a method that returns a new instance of an object every time you call it. I read the Guice user guide and didn't see an obvious way of how to do this. I'd like to have some code like this:

@Inject
private FooInstanceFactory fooInstanceFactory;

//...
    Foo foo = fooInstanceFactory.getNewInstanceOfFoo();
//...
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356

1 Answers1

2

This really isn't the Guice way of doing things. You can inject a Provider<Foo> and call Provider#get() on it, but the calling code shouldn't be concerned with whether or not you're getting a new instance each time. That's for the module's configuration to worry about.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • I (perhaps incorrectly) think of Guice as a way of removing the `new` keyword from my production logic. If I've got some production logic that's generating a JSON message and has lots of `new JSONObject()`'s in it, I need to be sure that each JSONObject I create is a new instance and not a singleton. How am I thinking about this the wrong way? – Daniel Kaplan Feb 25 '13 at 18:45
  • 1
    The place to ensure that each JSONObject is new is in the provider's logic, not in the consumer's logic. – Louis Wasserman Feb 25 '13 at 18:49
  • @LouisWasserman Not sure if I've interpreted your statement correctly. If `SpecificJSONMessageConstructor` needs build a deeply nested JSON message, doesn't the `SpecificJSONMessageConstructor` need to know that every new JSON object it constructs is a different instance from the previous one? I don't see how I could write my code in a way that that wouldn't matter. But if you're *simply* saying the `Provider` should `return new JSONObject()`, not the `SpecificJSONMessageConstructor`, then I think we're on the same page. – Daniel Kaplan Feb 25 '13 at 19:07
  • @tieTYT yes, "the `Provider` should `return new JSONObject()`" is one way to do it. You don't even need to explicitly implement such a provider with Guice – it can be generated automatically. You just need to configure your Guice module for `JSONObject` injection. If you're using `AbstractModule` (which you probably should), just add this line to the `configure()` method: `bind(JSONObject.class);` – Matt Ball Feb 25 '13 at 19:15
  • @MattBall Ooh, that's good to know. How do I get the provider? Do I just put `@Inject private Provider jsonProvider;` in the `SpecificJSONMessageConstructor` after I do that bind in the module? – Daniel Kaplan Feb 25 '13 at 19:21
  • Yes. Why don't you go and _try_ it? – Matt Ball Feb 25 '13 at 19:26
  • I tried it out. The `bind(...)` is unnecessary. You can just inject the provider. – Daniel Kaplan Feb 25 '13 at 20:32
  • +1. We can use ProtoType/Singleton/RequestScoped scopes on bean definition for the Object contained in provider to determine in what scope we need the new instance to be created. – bit_cracker007 Jul 28 '21 at 03:02