英文:
Kotlin init not picking up value from @Value
问题
private lateinit var needValueHere: String
@Value("${CLIENT_ID:NA}")
private val CLIENT_ID: String = ""
init {
this.needValueHere = this.CLIENT_ID
}
英文:
I want to initialise a member variable from a value I pick from ENV but it is not available in init block as it gets picked up after object initialisation
private lateinit var needValueHere: String
@Value("${CLIENT_ID:NA}")
private val CLIENT_ID: String = ""
init {
this.needValueHere = this.CLIENT_ID
}
This is a simplified version of the actual problem.
I have verified the value is available in the member functions.
答案1
得分: 1
您的对象是通过以下方式构建的:
- 创建对象(例如,调用构造函数)
- 通过反射:放置依赖项(例如,在@Autowired、@Value和其他注解下填充值)。
您的初始化块是构造函数的一部分,例如,所有与Spring相关的项都不会在这里初始化。
您可以如何修复这个问题:
- 将属性提取到类型安全的配置中(请参阅官方文档)
- 使用类似以下的类符号。
- 创建
private lateinit var
字段,直到Spring初始化完成后再调用它(这对于集成测试很有用,例如,测试方法仅在完全预热后开始)。另一种选项是使用kotlin lazy 符号。但是,整个项目不能被称为“好代码”。
class MyService(@Value("${CLIENT_ID:NA}") private val needValueHere: String) {
/* */
}
英文:
Your object is constructing by the following way:
- Create object (e.g. call constructor)
- Via reflection: put dependencies (e.g. fill values under @Autowired, @Value and other annotations).
Your init block is part of constructor, e.g. all Spring-related items aren't initialized here.
How you can fix this:
- Extract properties to the type-safe configuration (please see official docs here)
- Use notation of class like below.
- Create
private lateinit var
field and don't call it until Spring initialization finishing (this is useful for integration tests, e.g. test methods start only after full warmup). Another option - use kotlin lazy notation. However whole this item couldn't be named as "good code".
class MyService(@Value("${CLIENT_ID:NA}") private val needValueHere: String) {
/* */
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论