gpt4 book ai didi

java - 如何在 Guice 中为变量设置默认值

转载 作者:行者123 更新时间:2023-11-30 02:50:52 25 4
gpt4 key购买 nike

就像我们在 Spring 中执行以下操作

@Value("${varName:0}")
int varName;

有没有办法使用 Google Guice 来做到这一点?

最佳答案

在 Guice 中,您可以注释该方法并使其可选。然后您只需分配默认值即可。如果没有要注入(inject)的属性,则它将是默认值。

例如:

public class TestModule3 extends AbstractModule {

@Override
protected void configure() {

// Properties p = new Properties();
// p.setProperty("myValue", "12");
// Names.bindProperties(binder(), p); // this binds the properties that usually come for a file

bind(Manager.class).to(ManagerImpl.class).in(Singleton.class);
}

public static interface Manager {
public void talk();
}

public static class ManagerImpl implements Manager {

@Inject(optional = true)
@Named("myValue")
int test = 0;

@Override
public void talk() {
System.out.println(test);
}
}

public static void main(String[] args) {

Manager instance = Guice.createInjector(new TestModule3()).getInstance(Manager.class);
instance.talk();

}
}

这将为您打印“0”,因为我注释掉了属性绑定(bind)。如果删除注释,它会将值 12 绑定(bind)到字符串 myValue。注入(inject)注释负责剩下的事情。

希望有帮助,

编辑:

正如@TavianBarnes 指出的,Guice 4+ 有一个OptionalBinder。我针对您的用例尝试了此方法,但无法使其开箱即用。

看来OptionalBinding对于类(实际实例)非常有用,而不是对于属性。原因如下:

  1. 您必须提前了解所有属性并将它们绑定(bind)到默认值。人们很容易忘记它们。 OP 所示的示例还表明,他不知道自己是否拥有可用的属性(根据名称)。

  2. 属性绑定(bind)的默认实现不能与OptionalBinding 结合使用。

因此,实现该功能的方法如下:

        OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, Names.named("myValue"))).setDefault()
.toInstance("777");

Properties p = new Properties();
p.setProperty("myValue", "12");

// use enumeration to include the default properties
for (Enumeration<?> e = p.propertyNames(); e.hasMoreElements();) {
String propertyName = (String) e.nextElement();
String value = p.getProperty(propertyName);

OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, Names.named(propertyName))).setBinding()
.toInstance(value);

}

我必须复制命名绑定(bind)代码并将其更改为支持可选绑定(bind)。

总结:

  1. 我更愿意在属性代码中使用Optional=true 标志+默认值。

  2. 对可选的实际类使用OptionalBinding。

最后,您还可以做一件事 - 这是我的代码中的解决方案。我有类似的要求(不是可选的,而是默认值)。

我想要:

  1. 绑定(bind)我的属性
  2. 检查我的属性是否是变量
  3. 替换变量
  4. 如果变量不可用,请设置默认值

Apache 已经为此提供了一个方便的库,我已经重用了它。这是我的属性的样子:

myProperty=${ENV_VAR_NAME:-600}

这是如何定义默认值的默认注释。上面的属性说:

  1. 使用环境变量“ENV_VAR_NAME”。
  2. 如果未设置“ENV_VAR_NAME”,则使用值“600”

然后我将其绑定(bind)如下:

        InputStream resourceAsStream = getClass().getResourceAsStream(path);
if(resourceAsStream == null) {
throw new IllegalArgumentException("No property file found for path: " + path);
}
try {
p.load(resourceAsStream);
EnvironmentVariableSubstitutor envSubstitutor = new EnvironmentVariableSubstitutor(false);
Set<Object> keys = p.keySet();
for(Object k : keys) {
String property = p.getProperty(k.toString());
property = envSubstitutor.replace(property);
p.put(k, property);
}

} catch (IOException e) {
throw new IllegalStateException("Could not load properties", e);
} finally {
try {
resourceAsStream.close();
} catch (IOException e) {
log.error("Could not close stream for resource " + path);
}
}

Names.bindProperties(binder(), p);

这段代码的作用是:

  1. 从资源文件加载属性
  2. 使用EnvironmentVariableSubstitutor 处理属性值并覆盖结果。 (参见循环)
  3. 最后,将修改后的属性与其名称绑定(bind)。

这些是我可以在短时间内想出的所有解决方案:)如果有不清楚的地方请告诉我

编辑2:

还有一些关于OptionalBindings和属性的信息+如何处理这个谷歌线程中的默认值:https://groups.google.com/forum/#!topic/google-guice/7Ga79iU_sb0

阿图尔

关于java - 如何在 Guice 中为变量设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38703732/

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