Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind String to variable in Guice?

Tags:

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?

like image 610
eric2323223 Avatar asked Oct 14 '09 07:10

eric2323223


People also ask

What does bind do in Guice?

Guice Basic Bindings. Binding is to Guice as wiring is to Spring. With bindings, we define how Guice is going to inject dependencies into a class. This module implementation specifies that an instance of DefaultCommunicatorImpl is to be injected wherever a Communicator variable is found.

What is @named annotation in Guice?

Dependency Injection for Java Developers with Dagger & Guice Guice provides another way also to map bindings without creating a custom annoation. It allows so using @Named annotation.

What is @inject annotation in Guice?

@Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values. The Injector fulfills injection requests for: Every instance it constructs.


1 Answers

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.

like image 58
NamshubWriter Avatar answered Oct 25 '22 02:10

NamshubWriter