Wudong
Wudong

Reputation: 2360

Google Guice custom scope

Just a quick question see if I understand scope correctly.

I understand that scope is to control how/when the instance is created. Now I have a class in an application, and I want two instance of it; each one will be injected to some other instance.

Is it possible in Guice to create two scopes, for each of the instance? and then I can inject each of the scoped instance to any other instance as I like?

Upvotes: 4

Views: 960

Answers (1)

Tim Gage
Tim Gage

Reputation: 1381

Scopes:

  1. Scopes allow you to control the lifecycle of an object.

  2. You can only bindScope() a scope annotation once. The concept of a scope is injector-level: It's wiring configuration.

  3. You can bind multiple things (keys) into once scope.

  4. You can define as many scopes as you want, but each binding can only be in one scope.

You haven't given the full details of your problem, but it is my experience that in most cases where a custom scope appears initially to be the right answer, it rarely actually is!

Perhaps what you want is to annotate two instances of one type? Something like:

bind(SomeService.class).in(First.class).to(FirstServiceImpl.class);
bind(SomeService.class).in(Second.class).to(SecondServiceImpl.class);

Then you can inject the one you want:

@Inject
SomeConstructor(@First SomeService service) {
}

or:

@Inject
SomeConstructor(@Second SomeService service) {
}

If that doesn't help then you might need to give some more detail of your problem.

Upvotes: 5

Related Questions