指南,从属性获取值时的类型转换



下面的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自动在幕后为我做这些?

我通过查阅Guice源代码找到了一个解决方案,尽管我不得不说它不是最漂亮的(稍后会详细介绍)。

首先,我们需要创建一个TypeConverter

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeConverter;
// Omitted: other imports
public class ColorTypeConverter implements TypeConverter {
@Override
public Object convert(String value, TypeLiteral<?> toType) {
if (!toType.getRawType().isAssignableFrom(Color.class)) {
throw new IllegalArgumentException("Cannot convert type " + toType.getType().getTypeName());
}
if (value == null || value.isBlank()) {
return null;
}
return Color.decode(value);
}
}

然后,一个Matcher。我一般。

import com.google.inject.TypeLiteral;
import com.google.inject.matcher.AbstractMatcher;
// Omitted: other imports
public class SubclassMatcher extends AbstractMatcher<TypeLiteral<?>> {
private final Class<?> type;
public SubclassMatcher(Class<?> type) {
this.type = type;
}
@Override
public boolean matches(TypeLiteral<?> toType) {
return toType.getRawType().isAssignableFrom(type);
}
}

最后,向Guice模块添加以下行:

import com.google.inject.AbstractModule;
// Omitted: other imports
public class ExampleModule extends AbstractModule {
@Override
protected void configure() {
binder().convertToTypes(new SubclassMatcher(Color.class), new ColorTypeConverter());
// Omitted: other configurations
}
}
现在,下面的注入工作了。
public class Example {
@Inject
@Named("com.example.background-color")
private Color backgroundColor;
}

它可以更漂亮。存在一个com.google.inject.matcher.MatchersAPI,我无法使用,可以解决我的问题,而不构建我的个人SubclassMatcher类。参见Matchers.subclassesOf(Class<?>)。这当然是我的错,因为我不相信Google不会想到这个非常常见的用例。如果你找到了一个可行的方法,请留下评论。

Guice不能为你做这些。

我认为从Stringint的转换发生在注入时,而不是在调用Names.bindProperties(...)

参见bindProperties方法:

/** Creates a constant binding to {@code @Named(key)} for each entry in {@code properties}. */
public static void bindProperties(Binder binder, Map<String, String> properties) {
binder = binder.skipSources(Names.class);
for (Map.Entry<String, String> entry : properties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
binder.bind(Key.get(String.class, new NamedImpl(key))).toInstance(value);
}
}
/**
* Creates a constant binding to {@code @Named(key)} for each property. This method binds all
* properties including those inherited from {@link Properties#defaults defaults}.
*/
public static void bindProperties(Binder binder, Properties properties) {
binder = binder.skipSources(Names.class);
// use enumeration to include the default properties
for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
String propertyName = (String) e.nextElement();
String value = properties.getProperty(propertyName);
binder.bind(Key.get(String.class, new NamedImpl(propertyName))).toInstance(value);
}
}

它们只是绑定字符串。

您可以复制其中一个并创建自己的绑定。如果属性值是颜色格式,则将其额外绑定为Color

例如:

public class GuiceColors {
public static class GameModule extends AbstractModule {
@Override
protected void configure() {
Properties props = new Properties();
try {
props.load(getClass().getResourceAsStream("application.properties"));
} catch (IOException e) {
e.printStackTrace();
}
bindPropertiesWithColors(props);
}
private void bindPropertiesWithColors(Properties properties) {
Binder binder2 = binder().skipSources(Names.class);
// use enumeration to include the default properties
for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
String propertyName = (String) e.nextElement();
String value = properties.getProperty(propertyName);
try {
Color decodedColor = Color.decode(value);
binder2.bind(Key.get(Color.class, Names.named(propertyName)))
.toInstance(decodedColor);
} catch (NumberFormatException ex) {
// property value cannot be decoded as color, ignore the exception
}
binder2.bind(Key.get(String.class, Names.named(propertyName))).toInstance(value);
}
}
}
public static class Example {
@Inject
@Named("com.example.background-color")
private Color color;
@Inject
@Named("com.example.background-color")
private String colorString;
}
public static void main(String[] args) {
Injector injector = Guice.createInjector(new GameModule());
System.out.println(injector.getInstance(Example.class).color);
System.out.println(injector.getInstance(Example.class).colorString);
}
}

application.properties为:

com.example.background-color = 0x333333

最新更新