java Guice 和属性文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3071891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:13:16  来源:igfitidea点击:

Guice and properties files

javadependency-injectionguice

提问by benstpierre

Does anybody have an example of how to use Google Guice to inject properties from a .properties file. I was told Guice was able to validate that all needed properties exist when the injector starts up.

有没有人有如何使用 Google Guice 从 .properties 文件注入属性的示例。我被告知 Guice 能够在注入器启动时验证所有需要的属性是否存在。

At this time I cannot find anything on the guice wiki about this.

目前我在 guice wiki 上找不到任何关于此的信息。

回答by ColinD

You can bind properties using Names.bindProperties(binder(), getProperties()), where getPropertiesreturns a Propertiesobject or a Map<String, String>(reading the properties file as a Propertiesobject is up to you).

您可以使用 来绑定属性Names.bindProperties(binder(), getProperties()),其中getProperties返回一个Properties对象或一个Map<String, String>(将属性文件作为Properties对象读取由您决定)。

You can then inject them by name using @Named. If you had a properties file:

然后,您可以使用@Named. 如果您有一个属性文件:

foo=bar
baz=true

You could inject the values of those properties anywhere you wanted, like this:

你可以在任何你想要的地方注入这些属性的值,像这样:

@Inject
public SomeClass(@Named("foo") String foo, @Named("baz") boolean baz) {...}

Guice can convert values from strings to the type being injected, such as the booleanabove, automatically (assuming the string is an appropriate format). This works for primitive types, enums and class literals.

Guice 可以自动将值从字符串转换为被注入的类型,例如boolean上面的类型(假设字符串是适当的格式)。这适用于原始类型、枚举和类文字。