guice provides a way to create bindings with value objects or constants. consider the case where we want to configure jdbc url.
inject using @named annotation
@inject
public void connectdatabase(@named("jbdc") string dburl) {
//...
}
this can be achived using toinstance() method.
bind(string.class).annotatedwith(names.named("jbdc")).toinstance("jdbc:mysql://localhost:5326/emp");
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.name.named;
import com.google.inject.name.names;
public class guicetester {
public static void main(string[] args) {
injector injector = guice.createinjector(new texteditormodule());
texteditor editor = injector.getinstance(texteditor.class);
editor.makeconnection();
}
}
class texteditor {
private string dburl;
@inject
public texteditor(@named("jdbc") string dburl) {
this.dburl = dburl;
}
public void makeconnection(){
system.out.println(dburl);
}
}
//binding module
class texteditormodule extends abstractmodule {
@override
protected void configure() {
bind(string.class)
.annotatedwith(names.named("jdbc"))
.toinstance("jdbc:mysql://localhost:5326/emp");
}
}
output
compile and run the file, you will see the following output.
jdbc:mysql://localhost:5326/emp