首页 > 解决方案 > Kotlin 弹簧靴。控制器类@Validated 导致@Autowired 的服务失败

问题描述

我使用@Validatedon HomeController,然后@AutowiredUserService 失败。我在下面得到异常

kotlin.UninitializedPropertyAccessException: lateinit property service has not been initialized
    at com.example.demo.web.HomeController.getService(HomeController.kt:16) ~[main/:na]
    at com.example.demo.web.HomeController.index(HomeController.kt:20) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke...

这是我的代码

HoneController.kt

@Validated
@RestController
open class HomeController {

    @Autowired
    lateinit var service: UserSercie

    @RequestMapping("/")
    fun index(@NotNull(message = "name can not be null") name: String): String {
        return "hello " + name + service.getData()
    }
}

用户服务.kt

@Service
class UserSercie {

    fun getData(): String {
        return " message from service"
    }
}

build.gralde

plugins {
    id 'org.springframework.boot' version '2.4.5'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.5.0'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
}

test {
    useJUnitPlatform()
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "11"
    }
}
compileTestKotlin {
    kotlinOptions {
        jvmTarget = "11"
    }
}

标签: spring-bootvalidationkotlinserviceautowired

解决方案


我找到kotlin-spring plugin了:https://kotlinlang.org/docs/all-open-plugin.html#spring-support

我使用插件并openHomeController. 然后它工作。

buildscript {

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:$springbootVersion")
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
    }
}

subprojects {

    apply plugin: 'java'
    apply plugin: 'war'
    apply plugin: 'kotlin'
    apply plugin: "kotlin-spring"
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'

    //other settings
}


推荐阅读