以下 Guice 模块将属性文件绑定到@Named
注释。
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
// Omitted: other imports
public class ExampleModule extends AbstractModule {
@Override
protected void configure() {
Names.bindProperties(binder(), getProperties());
}
private Properties getProperties() {
// Omitted: return the application.properties file
}
}
我现在可以将属性直接注入到我的类中。
public class Example {
@Inject
@Named("com.example.title")
private String title;
@Inject
@Named("com.example.panel-height")
private int panelHeight;
}
从属性文件中读取的值是字符串,但正如您在上面的示例中所见,Guice 能够对int
字段进行类型转换。
现在,给定com.example.background-color=0x333333
我希望能够为任意类获得相同类型转换的属性,例如:
public class Example {
@Inject
@Named("com.example.background-color")
private Color color;
}
假设Color
该类包含一个静态方法decode()
,我可以Color
通过调用Color.decode("0x333333")
.
如何将 Guice 配置为自动在幕后为我执行此操作?