Google Guice – Constant Bindings

Google Guice – Constant Bindings

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

Now, compile and run the file. You can see the following output −
jdbc:mysql://localhost:5326/emp

Comments

Popular posts from this blog

Mad Scientist Profits Review – A Legit Method To Make Money Online

Targeting Academy 2.0 (2019) Review

Holiday SocialPacks Review – Cash In By Helping People Fight Against Corporations