Guice-constant-bindings

提供:Dev Guides
移動先:案内検索

Google Guice-定数バインディング

Guiceは、値オブジェクトまたは定数を使用してバインディングを作成する方法を提供します。 JDBC URLを設定する場合を考えてください。

@Named注釈を使用して注入する

@Inject
public void connectDatabase(@Named("JBDC") String dbUrl) {
  //...
}

これは、* toInstance()*メソッドを使用して達成できます。

bind(String.class).annotatedWith(Names.named("JBDC")).toInstance("jdbc:mysql://localhost:5326/emp");

完全な例

GuiceTesterという名前のJavaクラスを作成します。

*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");
   }
}

出力

次に、ファイルをコンパイルして実行します。 次の出力を見ることができます-

jdbc:mysql://localhost:5326/emp