gpt4 book ai didi

java - Guice 将对象注入(inject)到类构造函数中

转载 作者:行者123 更新时间:2023-12-02 01:41:47 25 4
gpt4 key购买 nike

我刚刚开始寻找 Guice 的新项目。我有这样的东西

ConfigImpl 类和 Config 接口(interface)

 interface Config{...}

class ConfigImpl implements Config {
private static final Map<> propMap;
public ConfigImpl(Map<> propMap) {
this.propMap = someProps;
}
}

我想出的 Guice 注入(inject)

public class MyInjector extends AbstractModule {
protected void configure() {
bind(Config.class).to(ConfigImpl.class)
}
}

最后

public SomeClass {
Config someConfig;
Injector injector = Guice.createInjector(new MyInjector());
someConfig = injector.getInstance(Config.class);
}

现在我很困惑,因为我找不到将 propMap 传递到 ConfigImpl 类的方法。我想知道在 Guice 中执行此操作的正确方法。谢谢!

最佳答案

您应该从模块中注入(inject) propMaps:

public class MyInjector extends AbstractModule {
private final Map<String,String> mapProps;
public MyInjector(Map<String,String> mapProps) {
this.mapProps = mapProps;
}
protected void configure() {
bind(Config.class).to(ConfigImpl.class).in(Scope.SINGLETON); // You most than likely want this
bind(new TypeLiteral<Map<String,String>>() {}).toInstance(mapProps); // binding for the map.
}
}

并像这样使用它:

public class SomeClass {
void doSomething() {
Map<String,String> mapProps = ... ;
Injector injector = Guice.createInjector(new MyInjector(mapProps));
Config someConfig = injector.getInstance(Config.class);
}
}

此外,您应该修复您的 ConfigImpl 类:

class ConfigImpl implements Config {
private final Map<String,String> propMap;
@Inject // mandatory since you use a non-default constructor
public ConfigImpl(Map<String,String> propMap) { // add the generic type of the map
this.propMap = propMap;
}
}

关于java - Guice 将对象注入(inject)到类构造函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com