Alex Rivera | Logout

Guice injections on named string fields

Asked 2012-05-31T17:25:42.277
8

I have a class:

public class FizzBuzz {
    @Named("Red") private String redService;

    public static void main(String[] args) {
        GuiceTest testApp = new GuiceTest();

        testApp.run();
    }

    private void run() {
        Injector inj = Guice.createInjector(new MyModule());

        redService = (String)inj.getInstance(String.class);

        // Should print "red-service" but is instead an empty string!
        System.out.println("redService = " + redService);
    }

    // ... Rest of class omitted for brevity
}

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(String.class).annotatedWith(Names.named("Red")).toInstance("red-service");
    }
}

In my module I instruct Guice to bind all String.class instances @Named "Red" to the string instance "red-service", however I'm not seeing that in the outputted print statement. How am I using Guice incorrectly?

Edit
Report

1 Answer

30

Let me just summarize some of the comments already made here ...

  1. You forgot the @Inject Annotation
  2. I would strongly advise to keep Guice/Injector outside of FizzFuzz. Use the static main method to bootstrap your App (not run()).
  3. Binding String to a constant can easily be done via bindConstant.

Ths brings you to something like this:

public class FizzFuzz {
    @Inject
    @Named("red")
    private String service;

    public static void main(String[] args) {
        FizzFuzz fizzFuzz = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bindConstant().annotatedWith(Names.named("red")).to("red-service");
            }    
        }).getInstance(FizzFuzz.class);

        System.out.println(fizzFuzz.service);
    }
}
answered 2012-06-01T14:17:22.080

Your Answer