问题描述
有没有人有一个例子说明如何使用Google Guice从.properties文件中注入属性。我被告知,Guice能够验证注射器启动时是否存在所有必需的属性。此时,我没有在guice wiki上找到任何内容。 p>
可以使用 Names.bindProperties(binder(),getProperties())
,其中 getProperties
返回一个属性
对象或 Map< String,String>
(读取属性文件为属性
对象取决于您)。
然后,您可以使用 @Named
以名称注入它们。如果您有一个属性文件:
foo = bar
baz = true
您可以在任意位置注入这些属性的值,如下所示:
@Inject
public SomeClass(@Named(foo)String foo,@Named(baz)boolean baz){...}
Guice可以将值从字符串转换为注入的类型,例如 boolean
以上,自动(假设字符串是适当的格式)。这适用于原始类型,枚举和类文字。
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.
At this time I cannot find anything on the guice wiki about this.
You can bind properties using Names.bindProperties(binder(), getProperties())
, where getProperties
returns a Properties
object or a Map<String, String>
(reading the properties file as a Properties
object is up to you).
You can then inject them by name using @Named
. If you had a properties file:
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 boolean
above, automatically (assuming the string is an appropriate format). This works for primitive types, enums and class literals.
这篇关于Guice和属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!