加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用Scala读取Spring Boot ConfigurationProperties

发布时间:2020-12-16 19:23:51 所属栏目:安全 来源:网络整理
导读:我在 Scala中使用Spring Boot.我想通过@ConfigurationProperties注释将属性读取到带有Scala类型的case类.我已经知道我将无法对Scala案例类进行注释,因为Spring Boot不支持基于构造的属性注入.但至少我想将集合(列表和映射)从配置映射到基于Scala的类型.这样
我在 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列表并附加到它.所以我肯定在这里走错了路.

我将不胜感激任何帮助.

解决方法

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
}

要么

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读