我如何使用 Kotlin 绑定 属性 值?
How can i bind property values using Kotlin?
使用 java,我可以像这样从 application.properties 文件中获取 "spring.datasource.url" 键的值:
@PropertySource("classpath:application.properties")
public class SpringJdbcConfig {
@Autowired
Environment environment;
private final String URL = "spring.datasource.url";
String dburl = environment.getProperty("spring.datasource.url");
}
使用 kotlin,这是不可能的:
@PropertySource("classpath:application.properties")
open class WebController {
@Autowired
var env: Environment ? = null
}
环境将不会引用 PropertySource 文件。
我如何在 kotlin 中使用它?
对于正在注入的字段,kotlin 提供了 lateinit 关键字。
如果您想从您的配置中读取一个值,spring 为您提供 @Value annotation
@Value("${my.property.key}")
lateinit var myValue: String
请注意,在 Java 中,您可以将 "${my.property.key}"
用作 "path",但由于 ${}
在 kotlin 中具有特殊含义,因此您必须转义 $
与 \
使用 java,我可以像这样从 application.properties 文件中获取 "spring.datasource.url" 键的值:
@PropertySource("classpath:application.properties")
public class SpringJdbcConfig {
@Autowired
Environment environment;
private final String URL = "spring.datasource.url";
String dburl = environment.getProperty("spring.datasource.url");
}
使用 kotlin,这是不可能的:
@PropertySource("classpath:application.properties")
open class WebController {
@Autowired
var env: Environment ? = null
}
环境将不会引用 PropertySource 文件。 我如何在 kotlin 中使用它?
对于正在注入的字段,kotlin 提供了 lateinit 关键字。
如果您想从您的配置中读取一个值,spring 为您提供 @Value annotation
@Value("${my.property.key}")
lateinit var myValue: String
请注意,在 Java 中,您可以将 "${my.property.key}"
用作 "path",但由于 ${}
在 kotlin 中具有特殊含义,因此您必须转义 $
与 \