Google Guice – Constant Bindings

Google Guice - Constant Bindings

This topic is about 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

Compile and run the file, you will see the following output.

jdbc:mysql://localhost:5326/emp

In this topic we learned about Google Guice – Constant Bindings. To know more, Click Here.

This Post Has One Comment

Leave a Reply