通用接口
public interface XConfig {
Properties properties = new Properties();
default Properties getProperties() {
return properties;
}
static <V> void setProperty(String key, V value) {
if (value instanceof String) {
properties.setProperty(key, (String) value);
} else if (value instanceof Class) {
properties.setProperty(key, ((Class<?>) value).getName());
} else {
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));
}
