Pages

Sunday, October 30, 2011

Inject in toInstance binding

With Guice it is extremely easy to add to injector self-constructed beans. But what was not very intuitive for me is that various inject annotations in these beans will have their influence on the state of the bean. Here is very simple illustration to this fact:

package com.sopovs.moradanen;

import javax.inject.Inject;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

public class ToInstanceTest {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new Module() {
            @Override
            public void configure(Binder binder) {
                binder.bind(String.class).toInstance("hello");
                binder.bind(Foo.class).toInstance(new Foo());
            }
        });
        Foo foo = injector.getInstance(Foo.class);
        System.out.println(foo.value);
    }

    private static class Foo {
        @Inject
        String value;
    }
}
The output of this java program is "hello". At first I was really surprised.

No comments:

Post a Comment