简体   繁体   English

Spring&Kotlin:构造函数和Lateinit注入之间有什么区别?

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

I had a problem with my application using spring an kotlin. 我在使用spring 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 : 不幸的是,这在我启动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 ! 使用tha代码可以正常工作! 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. 在我的情况下, lateinit var注入似乎运行良好。

Here's an example project for your reference: https://github.com/jivimberg/lateinit 这是一个示例项目供您参考: 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. 我怀疑您在初始化之前就引用了environment变量,这就是例外的原因。

It worked after the change. 更改后它起作用了。 It was because the environment variable was initialized in the primary constructor. 这是因为environment变量是在主构造函数中初始化的。 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. 从Spring Framework 4.3开始,具有单个构造函数的类的参数将自动自动装配,这就是为什么在上面显示的示例中不需要显式@Autowired构造函数的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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