google / google/guice

Automatic Type Conversion for Constant Binding fails in private modules.

Open
#427 0 comments 0 reactions 0 assignees View on GitHub
imported
Dominant language
Java
Stars
12.7k
Forks
1.7k
Avg merge
11m
Merged PRs (30d)
2

Description

_From [wcmatthysen](https://code.google.com/u/117782525564837192348/) on September 21, 2009 10:36:35_

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: http://code.google.com/p/google-guice/issues/detail?id=427_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.