简体   繁体   English

Guice和属性文件

[英]Guice and properties files

Does anybody have an example of how to use Google Guice to inject properties from a .properties file. 有没有人举例说明如何使用Google Guice从.properties文件中注入属性。 I was told Guice was able to validate that all needed properties exist when the injector starts up. 我被告知Guice能够验证喷射器启动时是否存在所有需要的属性。

At this time I cannot find anything on the guice wiki about this. 这时我在guice维基上找不到任何关于此事的内容。

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). 您可以使用Names.bindProperties(binder(), getProperties())绑定属性,其中getProperties返回Properties对象或Map<String, String> (将属性文件作为Properties对象读取取决于您)。

You can then inject them by name using @Named . 然后,您可以使用@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). Guice可以自动将字符串中的值转换为正在注入的类型(例如上面的boolean (假设字符串是适当的格式)。 This works for primitive types, enums and class literals. 这适用于原始类型,枚举和类文字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM