gpt4 book ai didi

spring - Kotlin 无法在使用 @Configuration @EnableWebMvc 注释的类中创建 @Autowired 字段

转载 作者:IT老高 更新时间:2023-10-28 13:43:01 25 4
gpt4 key购买 nike

Autowired 字段在初始化项目时为 null:

package com.lynas.config

import org.springframework.stereotype.Component
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


@Component
open class InterceptorConfig : HandlerInterceptorAdapter() {

override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any?): Boolean {

return true
}
}



package com.lynas.config

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter

@Configuration
@EnableWebMvc
@ComponentScan("com.lynas")
open class WebConfig() : WebMvcConfigurerAdapter() {

// this field show null
@Autowired
lateinit var interceptorConfig: InterceptorConfig

override fun addInterceptors(registry: InterceptorRegistry) {
registry.addInterceptor(interceptorConfig)
}

}

lateinit var interceptorConfig: InterceptorConfig 在我运行应用程序时为 null。如何解决这个问题?

完整代码https://github.com/lynas/kotlinSpringBug

最佳答案

尝试 @field:Autowired lateinit var interceptorConfig@set:Autowired 这将告诉 kotlin 编译器将注释显式地放在字段/ setter 上。默认情况下,它将它们放置在“属性”上,这是仅限 kotlin 的构造,Java 可能无法访问它。引用 kotlin docs here

关于spring - Kotlin 无法在使用 @Configuration @EnableWebMvc 注释的类中创建 @Autowired 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39856910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com