为什么想要实现
- 在写配置文件的时候, key并不能进行很好的提示
- 感觉配置文件过于关注底层, 例如:
- 在代码中可以使用
String.class.getName()
来获取全类名, 但是在配置文件中必须写成java.lang.String
- 在代码中可以使用
16*1024*1024
来表示16MB, 但是在配置文件中则必须自己将具体的数值计算出来
- 在代码中可以使用
综上原因, 提供一种从配置文件到配置类的实现方式
实现逻辑
- 设置接口
XConfig
- 配置类实现接口, 并重载初始化方法
init()
, 在其中进行属性的配置 - 通过工具类将各个配置类中的属性进行整合
通用接口
public interface XConfig {
Properties properties = new Properties();
default Properties getProperties() {
return properties;
}
/**
* 用来接收各种输入类型, 不需要在使用的时候进行考虑类型
*
* @param key
* @param value
* @param <V>
*/
static <V> void setProperty(String key, V value) {
if (value instanceof String) {
// value为字符串类型
properties.setProperty(key, (String) value);
} else if (value instanceof Class) {
// 如果是一个类的类型
properties.setProperty(key, ((Class<?>) value).getName());
} else {
// value为数值等其他基本类型
properties.setProperty(key, String.valueOf(value));
}
}
void init();
}
自定义配置类
public class XBaseConfig implements XConfig {
// 配置需要设置的各项配置属性
@Override
public void init() {
XConfig.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, "hadoop001:9092,hadoop002:9092,hadoop003:9092");
XConfig.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
XConfig.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
XConfig.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
XConfig.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
}
}
工具类
public class XUtils {
//整合所有的配置类
public static Properties getSystemResource(List<Class<? extends XConfig>> configClasses) {
Properties properties = new Properties();
try {
for (Class<? extends XConfig> configClass : configClasses) {
XConfig xConfig = configClass.newInstance();
xConfig.init();
Properties propertiesX = xConfig.getProperties();
propertiesX.forEach((key, value) -> properties.setProperty((String) key, (String) value));
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return properties;
}
}
使用示例
@Test
public void getConfigClassTest() {
// 这里可以添加多个配置类
List<Class<? extends XConfig>> classes = new ArrayList<>();
classes.add(XBaseConfig.class);
Properties properties = getSystemResource(classes);
properties.forEach((key, value) -> System.out.println(key + "=" + value));
}
测试结果: