24

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

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

Or I think it could be described this way:

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

mkobit
  • 43,979
  • 12
  • 156
  • 150
eric2323223
  • 3,518
  • 8
  • 40
  • 55
  • 2
    DI (dependency Injection) with all those tricks makes reading code harder, lost its origin goal. it is much easier NOT dependency inject in most cases, keep context in one place. This makes maintenance much easier. –  Aug 14 '13 at 23:19

4 Answers4

46

You first need to annotate the constructor for SomeClass:

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

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

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;
  }

Often, when you think you want to inject a String, you want to inject an object. For instance, if the String is a URL, I often inject a URI with a binding annotation.

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.

mkobit
  • 43,979
  • 12
  • 156
  • 150
NamshubWriter
  • 23,549
  • 2
  • 41
  • 59
23

This might be off-topic, but Guice makes configuration much easier than writing an explicit binding for every String you need. You can just have a config file for them:

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

and voilà all your config is ready for injection:

@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);
}

Now just create your Java properties file myconfig.properties at the root of your classpath with

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

or merge authorization information from some other source into the properties and you're set.

mkobit
  • 43,979
  • 12
  • 156
  • 150
Georg
  • 987
  • 8
  • 16
3

I was able to inject a string through Named annotation.

@Provides
@Named("stage")
String stage() {
    return domain;
}

class SomeClass {
   @Inject
   @Named("stage")
   String stageName;
}
Selvaram G
  • 727
  • 5
  • 18
0

I find a solution in the FAQ of Guice:

http://code.google.com/docreader/#p=google-guice&s=google-guice&t=FrequentlyAskedQuestions

In addition to define an annotation and a String attribute in MyModule, I need to write below line to get a instance of SomeClass:

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

But I remembered that Injector.getInstance() should not be used except for the root object, so is there any better way to do this?

mkobit
  • 43,979
  • 12
  • 156
  • 150
eric2323223
  • 3,518
  • 8
  • 40
  • 55