【问题标题】:how to load configuration file from build.gradle for a Kotlin application?如何从 build.gradle 为 Kotlin 应用程序加载配置文件?
【发布时间】:2019-06-27 15:45:07
【问题描述】:

我正在尝试做一个简单的 kotlin + dropwizard 应用程序。

我关注了一些在线信息,包括这个https://dev.to/tagmg/step-by-step-guide-to-building-web-api-with-kotlin-and-dropwizard

所以经过一些修改后,我创建了一个带有 build.gradle.kts 的应用程序,如下所示:

plugins {
    application
    kotlin("jvm")
    id("com.github.johnrengelman.shadow") version "4.0.3"
}

application {
    mainClassName = "path.MyApplication"
}


dependencies {
    implementation("... dependencies ...")
}

val shadowJar: ShadowJar by tasks

shadowJar.apply {
    mergeServiceFiles()
    manifest.attributes.apply {
        put("Main-Class", application.mainClassName)
    }
}

tasks.named<JavaExec>("run") {
    args("server", "local.yml")
}

在 MyApplication 我有这样的东西:

类 MyApplication : Application() {

companion object {
    @JvmStatic fun main(args: Array<String>) {
        MyApplication().run(*args)
    }
}

override fun run(configuration: MyConfiguration, environment: Environment) {

    val myResource = MyResource() //endpoints with dropwizard
    environment.jersey().register(myResource)
    }

} 

在我的配置中

class MyConfiguration(val serviceName: String
) : Configuration(){



}

问题...

当我做 gradlew run 时,我得到这个错误:

  * Failed to parse configuration; Cannot construct instance of `MyConfiguration` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: UNKNOWN; line: -1, column: -1]

我真的不知道为什么会出现这个错误,或者我的 local.yml 是否有问题

我的 local.yml 文件有这个:

serviceName: Kotlin Calculator

具有讽刺意味的是,当我将 : 更改为 = 时,我的应用程序就会运行。

知道这有什么问题吗?

【问题讨论】:

    标签: gradle kotlin dropwizard


    【解决方案1】:

    MyConfiguration 类应该有一个空的构造函数。将 serviceName 设为属性。

    class MyConfiguration() : Configuration(){
    
      @NotNull
      val serviceName: String = ""
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-25
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 2010-11-14
      • 2020-02-27
      相关资源
      最近更新 更多