Maven<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.1.0</version>
</dependency>
Kullanım
1. Bir Injector yaratılır. Injector'ı yaratırken AbstractModule nesnesi veririz.
2. Injector.getInstance(Foo.class) çağrısı ile @Inject anotasyonları doldurulmuş bir Foo nesnesi elde ederiz
3. Eğer Enforce Explicit Binding seçili değilse, Guice
JustInTimeBindings yapabilir. Yani AbstractModule tarafından bilinmeyen veya anotasyon ile işaretlenmemiş nesneleri de yaratabilir.
Örnek
Injector injector = Guice.createInjector(new BasicModule());
Communication comms = injector.getInstance(Communication.class);
Injector Sınıfı
AbstractModule Sınıfı
Singleton Kullanımı
Singleton 3 farklı şekilde yapılabilir.
1. At Class level
Örnek
@Singleton
class SpellCheckerImpl implements SpellChecker {
@Override
public void checkSpelling() {
...
}
}
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class);
}
}2. At Configuration level
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {
bind(SpellChecker.class).to(SpellCheckerImpl.class).in(Singleton.class);
}
}3. At Method level
class TextEditorModule extends AbstractModule {
@Override
protected void configure() {}
@Provides @Singleton
public SpellChecker provideSpellChecker() {
SpellChecker spellChecker = new SpellCheckerImpl();
return spellChecker;
}
}