【发布时间】:2021-08-07 06:06:50
【问题描述】:
我在HomeController 上使用@Validated,然后用户服务的@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...
- Spring Boot
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.grade
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-boot validation kotlin service autowired