2016-10-04 8 views
7

Autowiredフィールドでアノテートされているクラスで@Autowiredフィールドを作成することはできませんすることはnullです:私は、アプリケーションを実行するとKotlinは@Configuration @EnableWebMvc

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

+0

あなたはSpring Bootを使用していますか?もしそうなら、ブートストラップクラスはどこにありますか?ルートパッケージとサブパッケージ内の他のすべてのコンポーネントの内部に配置することをお勧めします。おそらく、コンポーネントのスキャンが正しく動作していない可能性があります。 '@ EnableWebMvc'と' @ ComponentScan'をひとつの '@ SpringBootApplication'で置き換えることもできます。詳細については、https://spring.io/blog/2016/02/15/developing-spring-boot-applications-with-kotlinも参照してください。 –

+0

その春の起動アプリケーションではない – LynAs

+0

'@ Autowired'はプライベートフィールドにあります。これはSpringにとっては問題ありません。おそらく、あなたのアプリケーションの残りの部分をチェックしてください、設定、クラスパスのスキャンなどをspingする必要があります。私はKotlin固有の問題であるものは何も表示されません。 –

答えて

1

は、フィールド/セッターに明示的に注釈を入れてkotlinコンパイラを教えてくれます@field:Autowired lateinit var interceptorConfigまたは@set:Autowiredを試してみてください。デフォルトでは、それらをkotlin-only構文である "property"に配置し、Javaにアクセスする際に問題が発生する可能性があります。 kotlin docs here

+0

良い検索ができません。同じエラーが発生しました。 'lateinitのプロパティinterceptorConfigが初期化されていません。 – LynAs