【问题标题】:Spring & kotlin : What is the difference between constructor and lateinit injection?Spring&kotlin:构造函数和lateinit注入有什么区别?
【发布时间】:2017-08-27 14:00:30
【问题描述】:

我在使用 spring an kotlin 的应用程序时遇到了问题。一开始我有一个控制器和一个这样的服务:

这里是服务:

@Service
class StuffService {

    @Inject
    lateinit var environment : Environment

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

}

这是控制器:

@RestController
class StuffController {

    @Inject
    lateinit var stuffService : StuffService

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

}

不幸的是,当我启动 springboot 时,这给了我这个错误:

kotlin.UninitializedPropertyAccessException: lateinit property environment has not been initialized

所以我尝试通过构造函数注入:

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

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

有了这个代码就可以了!我没有错误。

我想知道有什么区别。我不明白发生了什么。谁能帮我理解一下?

【问题讨论】:

  • 你在哪里访问environment
  • 在方法中做事。我把 [...] 因为它可以是任何东西。我已将 [...] 替换为 [此处使用环境变量的功能代码]。我可以是environment.getProperty("my.property")
  • 好吧,看起来没问题...@Autowired 可能没有什么不同?
  • 不,没有区别:/

标签: spring spring-boot kotlin


【解决方案1】:

我使用以下版本对此进行了测试:

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

在我的情况下,lateinit var 注入似乎工作正常。

这是一个示例项目供您参考:https://github.com/jivimberg/lateinit

【讨论】:

    【解决方案2】:

    我怀疑您甚至在初始化之前引用了 environment 变量,这就是异常的原因。

    更改后它起作用了。这是因为environment 变量是在主构造函数中初始化的。您可能想知道没有注释它是如何工作的。据此doc

    从 Spring Framework 4.3 开始,具有单个构造函数的类会自动自动装配参数,这就是上面示例中不需要显式 @Autowired 构造函数的原因。

    【讨论】:

      猜你喜欢
      • 2019-08-16
      • 1970-01-01
      • 2017-01-07
      • 2019-08-30
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      相关资源
      最近更新 更多