Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Can't create @Autowired field in Class that are annotated with @Configuration @EnableWebMvc

Tags:

spring

kotlin

Autowired field is null when initializing the project:

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 is null when I run the application. How to fix this?

full code https://github.com/lynas/kotlinSpringBug

like image 306
LynAs Avatar asked Oct 04 '16 15:10

LynAs


1 Answers

try @field:Autowired lateinit var interceptorConfig or @set:Autowired which will tell kotlin compiler to put annotations explicitly on field/setter. by default it places them on "property" which is kotlin-only construct and Java may have problems accessing it. refer to kotlin docs here

like image 69
mantrid Avatar answered Nov 16 '22 01:11

mantrid