google-code-export / google-guice

Automatically exported from code.google.com/p/google-guice
Apache License 2.0
2 stars 1 forks source link

Automatic Type Conversion for Constant Binding fails in private modules. #427

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Hi guys,

I have a situation where I need guice's type conversion code to handle a 
constant binding for me. However, the constant binding is declared in 
a private module:

public class Main {

    public static class Foo {

        private int bar;

        @Inject
        public Foo(@Named("foo") int bar) {
            this.bar = bar;
        }
    }

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {

                Module module = new PrivateModule() {

                    @Override
                    protected void configure() {
                        bindConstant().annotatedWith(Names.named("foo")).to(1);
                        expose(Key.get(Integer.class, Names.named("foo")));
                    }
                };
                install(module);
            }
        });

        Foo foo = injector.getInstance(Foo.class);

        System.out.println("bar: " + foo.bar);
    }
}

The abovementioned code works, but if I change the line:

bindConstant().annotatedWith(Names.named("foo")).to(1);

to

bindConstant().annotatedWith(Names.named("foo")).to("1");

it breaks with the error:

1) Could not expose() java.lang.Integer annotated with 
@com.google.inject.name.Named(value=foo), it must be explicitly bound.
  at net.cilib.froot.xml.Main$1$1.configure(Main.java:40)

which seems as though the type conversion stuff does not work correctly in 
private modules because the following code works fine:

public class Main {

    public static class Foo {

        private int bar;

        @Inject
        public Foo(@Named("foo") int bar) {
            this.bar = bar;
        }
    }

    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {

                Module module = new AbstractModule() {

                    @Override
                    protected void configure() {
                        bindConstant().annotatedWith(Names.named("foo")).to("1");
                    }
                };
                install(module);
            }
        });

        Foo foo = injector.getInstance(Foo.class);

        System.out.println("bar: " + foo.bar);
    }
}

Original issue reported on code.google.com by wcmatthy...@gmail.com on 21 Sep 2009 at 2:36