【问题标题】:How to inject non-Guice instance into Guice module如何将非 Guice 实例注入 Guice 模块
【发布时间】:2019-08-15 22:28:02
【问题描述】:

我希望能够在外部定义一个简单的 Config bean(例如在 Spring 中)并将其注入到 Guice 模块中。

有什么办法可以做到吗?

public class InjectionTest {

    @Test
    public void test() {
        // In reality this would be externally defined
        Config config = new Config("a", "b");

        AbstractModule module = new AbstractModule() {
            @Override
            protected void configure() {
                bind(Config.class).toInstance(config);
            }
        };

        Injector injector = Guice.createInjector(module);
        Thing instance = injector.getInstance(Thing.class);
    }

    static class Thing {
        final Config config;

        public Thing(Config config) {
            this.config = config;
        }
    }

    static class Config {
        final String a, b;

        public Config(String a, String b) {
            this.a = a;
            this.b = b;
        }
    }
}

测试失败:

com.google.inject.ConfigurationException:Guice 配置错误:

1) 在 guice.InjectionTest$Thing 中找不到合适的构造函数。 > 类必须有一个(并且只有一个)用@Inject 注释的构造函数,或者一个非私有的零参数构造函数。 在 guice.InjectionTest$Thing.class(未知来源) 同时定位 guice.InjectionTest$Thing

1 个错误

【问题讨论】:

    标签: guice


    【解决方案1】:

    您在错误消息中有答案。

    类必须有一个(并且只有一个)带有注解的构造函数 @Inject 或非私有的零参数构造函数。

    Thing构造函数中添加@Inject注解

    @Inject
    public Thing(Config config) {
      this.config = config;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多