[英]Inject into static field Kotlin/Spring Boot
Im trying to inject a value into a static field in Kotlin, but I`m not having success. 我试图在Kotlin的静态字段中注入一个值,但是我没有成功。
I know a workaround with Java, so in Kotlin, what`s the equivalent for this Java code? 我知道Java的解决方法,因此在Kotlin中,此Java代码等效于什么?
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
Thought this was gonna work: 以为这会工作:
@Component
class GlobalValue {
companion object {
@JvmStatic
lateinit var database: String
@Value("\${myprop.testing2}") set
}
}
But it doesn't, for some reason, possibly, because generated setter is final
, or because it goes through Companion
object, I don't know. 但是,由于某种原因,这可能不是因为生成的setter是final
,还是因为它通过了Companion
对象,我不知道。
This works tho: 这可以通过:
@Component
class GlobalValue {
companion object {
@JvmField
var database: String = "test"
}
@Value("\${myprop.testing2}")
fun setDatabase(db: String) {
database = db
}
}
Note the \\
in @Value
- it's because otherwise we would have a conflict with the language itself, such construct is already there. 注意@Value
的\\
-这是因为否则我们将与语言本身发生冲突,此类结构已经存在。 Also, you need to specify a default value, lateinit
is impossible with @JvmField
. 另外,您需要指定一个默认值, lateinit
不能使用@JvmField
。
Theoretically, the following should be equivalent: 从理论上讲,以下内容应等效:
@Component
class GlobalValue {
companion object {
@JvmField
lateinit var DATABASE: String
}
@Value("\${mongodb.db}")
fun setDatabase(db: String) {
DATABASE = db;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.