Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Spring Boot ConfigurationProperties with Scala

I'm using Spring Boot in Scala. I would like to read properties via @ConfigurationProperties annotation to case classes with Scala types. I already know that I won't be able to annotate Scala case classes, beacause Spring Boot does not support construction-based injection of properties. But at least I would like to map collections (lists and maps) from the config to Scala based types. So that I can write a config class:

@Component
@ConfigurationProperties("kafka")
case class KafkaConfig() {
  @BeanProperty
  var bootstrapServers: List[String] = _

}

And write a config file application.yml like this:

kafka:
  bootstrapServers:
    - "node1:9092"
    - "node2:9092"

Is that possible at all? I've tried to use Converters for this case, like this:

import org.springframework.core.convert.converter.Converter
import scala.collection.JavaConverters._

@Component
@ConfigurationPropertiesBinding
class JavaListToList extends Converter[java.util.List[Any], List[Any]] {
  override def convert(s: java.util.List[Any]): List[Any] = {
    s.asScala.toList
  }
}

But that doesn't work, because Spring tries to not convert an already read (java) list, but to instantiate an empty Scala list and append to it. So for sure I'm going a wrong way here.

I will appreciate any help with this.

like image 852
zarzyk Avatar asked Nov 09 '22 04:11

zarzyk


1 Answers

import java.util.{List => JList, ArrayList => JArrayList}

@Configuration
@ConfigurationProperties("kafka")
class AppConfig {

 @BeanProperty
 var bootstrapServers: JList[String] = new JArrayList[String]

 def getBootStrapServer: JList[String]  = bootstrapServers
}

or

import java.util.{List => JList, ArrayList => JArrayList}

@Component
@ConfigurationProperties(prefix = "kafka")
class KafkaConfig {

 @BeanProperty
 var bootstrapServers: JList[String] = new JArrayList[String]

 def getBootStrapServer: JList[String]  = bootstrapServers
}
like image 55
Eliko Avatar answered Nov 15 '22 08:11

Eliko