【发布时间】:2023-04-11 08:32:02
【问题描述】:
以下 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.decode("0x333333") 获得一个新的Color 实例。
如何将 Guice 配置为自动在幕后为我执行此操作?
【问题讨论】: