Guice 简明教程

Google Guice - Constant Bindings

Guice 提供了一种通过值对象或常量创建绑定信息的方法。以我们想配置 JDBC url 为例。

Inject using @Named annotation

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

这可以通过 toInstance() 方法实现。

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

Complete Example

创建名为 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");
   }
}

Output

编译运行该文件,您会看到以下输出内容。

jdbc:mysql://localhost:5326/emp