如何绑定字符串变量吉斯? [英] How to bind String to variable in Guice?

查看:170
本文介绍了如何绑定字符串变量吉斯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来Guice和这里是一个幼稚的问题。我了解到,我们可以通过绑定字符串到一个特定的值:

I'm new to Guice and here is a naive question. I learned that we could bind String to a particular value through:

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

但如果我要绑定字符串任何可能charactors?

But what if I want to bind String to any possible charactors?

或者我认为这可能是desribed是这样的:

Or I think it could be desribed this way:

我怎么能代替新SomeClass的(字符串strParameter)与吉斯?

How can I replace "new SomeClass(String strParameter)" with Guice?

推荐答案

您首先需要对注释的构造 SomeClass的

You first need to annotate the constructor for SomeClass:

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

我preFER使用自定义的注释,如下所示:

I prefer to use custom annotations, like this:

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

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

然后,你需要提供你的模块绑定:

Then you need to provide a binding in your Module:

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

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

随后的时间吉斯创建SomeClass的,它会注入参数。例如,如果SomeOtherClass取决于SomeClass的:

Then an time Guice creates SomeClass, it will inject the parameter. For instance, if SomeOtherClass depends on SomeClass:

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

通常情况下,当你觉得你要注入一个字符串,要注入的对象。例如,如果该字符串的URL,我经常注入 URI 有约束力的注释。

这一切都假定有你可以在模块创建时的字符串定义了一些恒定值。如果值是不可用的模块创建时,您可以使用 AssistedInject

This all assumes there is some constant value you can define at module creation time for the String. If the value isn't available at module creation time, you can use AssistedInject.

这篇关于如何绑定字符串变量吉斯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆