我在HomeController
上使用@Validated
,然后UserService的@Autowired
失败。我在下面得到异常
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...
- 弹簧引导
2.4.5
- 科特林
1.5.0
- 渐变
6.8.3-bin
这是我的代码
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()
}
}
UserService.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"
}
}
我找到kotlin-spring plugin
:https://kotlinlang.org/docs/all-open-plugin.html#spring-支持
我使用插件并删除了HomeController
中的open
。那么它就起作用了。
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
}