Google Guice - 使用generic作为注入字段的参数

时间:2013-08-19 23:01:26

标签: java generics dependency-injection guice

我想为注入的字段使用类的泛型参数,但是guice会抱怨未绑定的键。是否可以在Test2中注入该字段?

示例:

public static class Test1<T1> {
    }

    public static class Test2<T2> {
        @Inject
        public Test1<T2> test;
    }

    public static void main(String[] args) throws Exception {
        Injector injector = Jsr250.createInjector(Stage.PRODUCTION, new TestModule());
        Test2<String> test = injector.getInstance(Key.get(new TypeLiteral<Test2<String>>(){}));
    }

    private static class TestModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(new TypeLiteral<Test1<String>>(){}).toInstance(new Test1<String>());
            bind(new TypeLiteral<Test2<String>>(){}).toInstance(new Test2<String>());
        }
    }

1 个答案:

答案 0 :(得分:0)

嗯,这对java泛型来说太过分了。即使没有注入,您的代码也无法运行,因为Test1<T2>无法匹配Test1<String>。您应该考虑不同的方法,尝试使用Annotation binding,如:

public static class Test2 {
        @Inject @Named("T2")
        public Test1<someGenericInterface> test;
    }

bind(new TypeLiteral<Test1<someGenericInterface>>(){}).annotatedWith(Names.named("T2")).toInstance(new Test1<T2>()); //T2 implements someGenericInterface
bind(new TypeLiteral<Test1<someGenericInterface>>(){}).annotatedWith(Names.named("T1")).toInstance(new Test1<T1>()); //T1 implements someGenericInterface

或实施特定的提供商Provider bindings或使用MapBinder