使用Scala读取Spring Boot ConfigurationProperties

时间:2016-12-21 13:20:56

标签: scala spring-boot

我在Scala中使用Spring Boot。我想通过@ConfigurationProperties注释将属性读取到带有Scala类型的case类。我已经知道我无法对Scala案例类进行注释,因为Spring Boot不支持基于构造的属性注入。但至少我想将集合(列表和映射)从配置映射到基于Scala的类型。这样我就可以编写一个配置类:

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

}

并编写一个配置文件application.yml,如下所示:

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

这有可能吗?我已尝试在这种情况下使用转换器,如下所示:

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
  }
}

但这并不起作用,因为Spring试图不转换已读取的(java)列表,而是实例化一个空的Scala列表并追加到它。所以我肯定在这里做错了路。

我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

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
}

int width = canvas.getWidth();
int height = canvas.getHeight();
Rect childRect = this.getChildRect();

Paint outerPaint = new Paint();
outerPaint.setColor(Color.LTGRAY);
borderPaint.setStyle(Paint.Style.FILL);


Paint innerPaint = new Paint();
innerPaint.setARGB(0, 0, 0, 0);
innerPaint.setAlpha(0);
innerPaint.setStyle(Paint.Style.FILL);

canvas.drawRect(0.0F, 0.0F, width, height, outerPaint);
canvas.drawRoundRect(new RectF(childRect.left, childRect.top, childRect.right, childRect.bottom), 8F, 8F, innerPaint);