标题不言自明,我有一个 Config 对象(来自 https://github.com/typesafehub/config),我想将它传递给一个只支持 java.util.Properties 作为参数的构造函数。 有没有一种简单的方法可以将 Config 转换为 Properties 对象?
最佳答案
这是一种将类型安全的 Config 对象转换为 Properties java 对象的方法。我只在创建 Kafka 属性的简单案例中对其进行了测试。
在 application.conf 中给出此配置
kafka-topics {
my-topic {
zookeeper.connect = "localhost:2181",
group.id = "testgroup",
zookeeper.session.timeout.ms = "500",
zookeeper.sync.time.ms = "250",
auto.commit.interval.ms = "1000"
}
}
您可以像这样创建相应的Properties 对象:
import com.typesafe.config.{Config, ConfigFactory}
import java.util.Properties
import kafka.consumer.ConsumerConfig
object Application extends App {
def propsFromConfig(config: Config): Properties = {
import scala.collection.JavaConversions._
val props = new Properties()
val map: Map[String, Object] = config.entrySet().map({ entry =>
entry.getKey -> entry.getValue.unwrapped()
})(collection.breakOut)
props.putAll(map)
props
}
val config = ConfigFactory.load()
val consumerConfig = {
val topicConfig = config.getConfig("kafka-topics.my-topic")
val props = propsFromConfig(topicConfig)
new ConsumerConfig(props)
}
// ...
}
propsFromConfig 函数是您主要感兴趣的,关键点是使用entrySet 来获取扁平化的属性列表,以及展开条目值,给出一个对象,其类型取决于配置值。
关于java - 将类型安全配置类型转换为 java.util.Properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337782/