Kotlin无法在类中使用@Configuration @EnableWebMvc注释创建@Autowired字段
初始化项目时,自动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
当我运行应用程序时, lateinit var interceptorConfig: InterceptorConfig
为null
。 如何解决这个问题?
完整的代码https://github.com/lynas/kotlinSpringBug
尝试@field:Autowired lateinit var interceptorConfig
或@set:Autowired
,它会告诉kotlin编译器在field / setter上显式地添加注释。 在默认情况下,它将它们放在仅属于kotlin的“属性”上,而Java可能在访问时遇到问题。 请参阅这里的kotlin文档