Ex 08 - Guice

ds_a
Neuling
Neuling
Beiträge: 1
Registriert: 23. Jun 2012 15:09

Ex 08 - Guice

Beitrag von ds_a »

I have difficulties understanding the dependency injection with guice. I understand that an Interface can be bound to an Implementation, such as:

Code: Alles auswählen

bind(MailServcer.class).to(CompanyInternalMailServer.class)
But what happens if the implementation has a parametrized constructor, such as:

Code: Alles auswählen

FileAddressBook addressBook = new FileAddressBook("resources/addressbook.txt");
If I simply bind the interface to the Implementation, I will lose the argument:

Code: Alles auswählen

bind(AddressBook.class).to(FileAddressBook.class)
So the first question is: How can this be solved?

What makes it more difficult is that the TextEditor constructor needs a dynamic reference to it's Emailer:

Code: Alles auswählen

EnglishTextEditor textEditor = new EnglishTextEditor(this);
Is the only solution to remove the dynamic "this" reference out of the constructor?

Thanks,
Daniel

Benutzeravatar
Tigger
Kernelcompilierer
Kernelcompilierer
Beiträge: 404
Registriert: 26. Okt 2007 17:35
Wohnort: Hofheim
Kontaktdaten:

Re: Ex 08 - Guice

Beitrag von Tigger »

Try to annotate the FileAddressBook Constructor

Code: Alles auswählen

	 @Inject
    public FileAddressBook(@Named("addresses") String file) {...
and then bind them with

Code: Alles auswählen

bind(AddressBook.class).to(FileAddressBook.class);
bind(String.class).annotatedWith(Names.named("addresses")).toInstance("resources/addressbook.txt");

Benutzeravatar
sproksch
Computerversteher
Computerversteher
Beiträge: 346
Registriert: 15. Apr 2004 17:56

Re: Ex 08 - Guice

Beitrag von sproksch »

Another option is to bind the address book to a concrete instance:

Code: Alles auswählen

bind(AddressBook.class).toInstance(new FileAddressBook("resources/addressbook.txt"))

Antworten

Zurück zu „Archiv“