我有一些以下代码,并警告了producer
变量accessing non-final property in constructor
class KafkaService {
val producer: KafkaProducer<String, String>
init {
val props = Properties()
props[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = "127.0.0.1:9092"
props[ProducerConfig.CLIENT_ID_CONFIG] = "DemoProducer"
props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
producer = KafkaProducer(props)
}
fun sendToKafka(topic: String, message: String) {
val producerRecord: ProducerRecord<String?, String> = ProducerRecord(topic, null, message)
producer.send(producerRecord)
}
}
解决此问题的最佳方法是什么?
答案 0 :(得分:2)
您应该将producer
变量初始化为惰性变量:
class KafkaService {
val producer: KafkaProducer<String, String> by lazy {
val props = Properties()
props[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = "127.0.0.1:9092"
props[ProducerConfig.CLIENT_ID_CONFIG] = "DemoProducer"
props[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
props[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java.name
KafkaProducer(props)
}
fun sendToKafka(topic: String, message: String) {
val producerRecord: ProducerRecord<String?, String> = ProducerRecord(topic, null, message)
producer.send(producerRecord)
}
}
这样,您的变量将在您第一次访问它时被初始化,并且您将不会重新分配最终变量。 阅读this可以更好地理解。