as @provides method becomes more complex, these methods can be moved to seperate classes using provider interface.
class spellcheckerprovider implements provider<spellchecker>{
@override
public spellchecker get() {
string dburl = "jdbc:mysql://localhost:5326/emp";
string user = "user";
int timeout = 100;
spellchecker spellchecker = new spellcheckerimpl(dburl, user, timeout);
return spellchecker;
}
}
next step is to map the provider to type.
bind(spellchecker.class).toprovider(spellcheckerprovider.class);
see the complete example below.
complete example
create a java class named guicetester.
guicetester.java
import com.google.inject.abstractmodule;
import com.google.inject.guice;
import com.google.inject.inject;
import com.google.inject.injector;
import com.google.inject.provider;
public class guicetester {
public static void main(string[] args) {
injector injector = guice.createinjector(new texteditormodule());
texteditor editor = injector.getinstance(texteditor.class);
editor.makespellcheck();
}
}
class texteditor {
private spellchecker spellchecker;
@inject
public texteditor( spellchecker spellchecker) {
this.spellchecker = spellchecker;
}
public void makespellcheck(){
spellchecker.checkspelling();
}
}
//binding module
class texteditormodule extends abstractmodule {
@override
protected void configure() {
bind(spellchecker.class)
.toprovider(spellcheckerprovider.class);
}
}
//spell checker interface
interface spellchecker {
public void checkspelling();
}
//spell checker implementation
class spellcheckerimpl implements spellchecker {
private string dburl;
private string user;
private integer timeout;
@inject
public spellcheckerimpl(string dburl,
string user,
integer timeout){
this.dburl = dburl;
this.user = user;
this.timeout = timeout;
}
@override
public void checkspelling() {
system.out.println("inside checkspelling." );
system.out.println(dburl);
system.out.println(user);
system.out.println(timeout);
}
}
class spellcheckerprovider implements provider<spellchecker>{
@override
public spellchecker get() {
string dburl = "jdbc:mysql://localhost:5326/emp";
string user = "user";
int timeout = 100;
spellchecker spellchecker = new spellcheckerimpl(dburl, user, timeout);
return spellchecker;
}
}
output
compile and run the file, you will see the following output.
inside checkspelling. jdbc:mysql://localhost:5326/emp user 100