23

私はGuiceが初めてで、ここに素朴な質問があります。次の方法で String を特定の値にバインドできることを知りました。

bind(String.class)
        .annotatedWith(Names.named("JDBC URL"))
        .toInstance("jdbc:mysql://localhost/pizza");

しかし、可能な任意の文字に String をバインドしたい場合はどうすればよいでしょうか?

または、次のように説明できると思います。

「new SomeClass(String strParameter)」を Guice に置き換えるにはどうすればよいですか?

4

4 に答える 4

44

最初に のコンストラクターに注釈を付ける必要がありますSomeClass

class SomeClass {
  @Inject
  SomeClass(@Named("JDBC URL") String jdbcUrl) {
    this.jdbcUrl = jdbcUrl;
  }
}

次のようなカスタム注釈を使用することを好みます。

class SomeClass {
  @Inject
  SomeClass(@JdbcUrl String jdbcUrl) {
    this.jdbcUrl = jdbcUrl;
  }

  @Retention(RetentionPolicy.RUNTIME)
  @Target({ElementType.FIELD, ElementType.PARAMETER})
  @BindingAnnotation
  public @interface JdbcUrl {}
}

次に、モジュールでバインディングを提供する必要があります。

public class SomeModule extends AbstractModule {
  private final String jdbcUrl; // set in constructor

  protected void configure() {
    bindConstant().annotatedWith(SomeClass.JdbcUrl.class).to(jdbcUrl);
  }
}

次に、Guice が SomeClass を作成するときに、パラメーターを注入します。たとえば、SomeOtherClass が SomeClass に依存している場合:

class SomeOtherClass {
  @Inject
  SomeOtherClass(SomeClass someClass) {
    this.someClass = someClass;
  }

多くの場合、文字列を注入したいと思うときは、オブジェクトを注入したいと思うでしょう。たとえば、文字列が URL の場合、URIにバインディング アノテーションを挿入することがよくあります。

これはすべて、モジュールの作成時に文字列に対して定義できる定数値があることを前提としています。モジュールの作成時に値が利用できない場合は、AssistedInjectを使用できます。

于 2009-10-19T16:02:53.733 に答える
21

これはトピックから外れているかもしれませんが、Guice を使用すると、必要なすべての String に対して明示的なバインドを記述するよりも構成がはるかに簡単になります。それらの設定ファイルを持つことができます:

Properties configProps = Properties.load(getClass().getClassLoader().getResourceAsStream("myconfig.properties");
Names.bindProperties(binder(), configProps);

そしてほら、すべての設定が注入の準備ができています:

@Provides // use this to have nice creation methods in modules
public Connection getDBConnection(@Named("dbConnection") String connectionStr,
                                  @Named("dbUser") String user,
                                  @Named("dbPw") String pw,) {
  return DriverManager.getConnection(connectionStr, user, pw);
}

クラスパスのルートにJavaプロパティファイル を作成するだけですmyconfig.properties

dbConnection = jdbc:mysql://localhost/test
dbUser = username
dbPw = password

または、他のソースからの認証情報をプロパティにマージすれば、設定は完了です。

于 2015-02-04T22:38:10.273 に答える
0

Guice の FAQ で解決策を見つけました。

http://code.google.com/docreader/#p=google-guice&s=google-guice&t=よくある質問

MyModule で注釈と String 属性を定義することに加えて、SomeClass のインスタンスを取得するために次の行を記述する必要があります。

SomeClass instance = Guice.createInjector(new MyModule("any string i like to use")).getInstance(SomeClass.class);

しかし、ルート オブジェクト以外では Injector.getInstance() を使用してはならないことを思い出したので、これを行うためのより良い方法はありますか?

于 2009-10-14T15:23:21.543 に答える