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

时间:2016-10-04 15:59:49

标签: spring kotlin

初始化项目时,

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: InterceptorConfignull。如何解决这个问题?

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

1 个答案:

答案 0 :(得分:2)

尝试@field:Autowired lateinit var interceptorConfig@set:Autowired,它会告诉kotlin编译器在field / setter上明确地添加注释。默认情况下,它将它们放在“属性”上,该属性是仅限kotlin的构造,Java可能在访问它时遇到问题。参考kotlin docs here