简体   繁体   中英

Spring & kotlin : What is the difference between constructor and lateinit injection?

I had a problem with my application using spring an kotlin. At the beginning I had one controller and one service like this :

Here is the service :

@Service
class StuffService {

    @Inject
    lateinit var environment : Environment

    fun doStuff() = [HERE FUNCTION CODE USING environment VARIABLE]

}

Here is the controller :

@RestController
class StuffController {

    @Inject
    lateinit var stuffService : StuffService

    @RequestMapping("/doStuff")
    fun doStuff() = stuffService.doStuff()

}

Unfortunately this give me this error when I start springboot :

kotlin.UninitializedPropertyAccessException: lateinit property environment has not been initialized

So I tried to inject via constructor :

@Service
class StuffService(val environment : Environment) {...}

@RestController
class StuffController(val stuffService: StuffService) {...}

With tha code it works ! I have no error.

I wonder what is the difference. I do not understand what happened. Can anyone help me to understand ?

I tested this with the following versions:

kotlinVersion = '1.2.20'
springBootVersion = '2.0.1.RELEASE'

And lateinit var injection seems to be working fine in my case.

Here's an example project for your reference: https://github.com/jivimberg/lateinit

I suspect that you are referencing the environment variable before it's even been initialized, that's why the exception.

It worked after the change. It was because the environment variable was initialized in the primary constructor. You may wonder how it worked without annotation. According to this doc

As of Spring Framework 4.3, classes with a single constructor have their parameters automatically autowired, that's why there is no need for an explicit @Autowired constructor in the example shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM