如何使用 Kotlin 绑定属性值?

zum*_*000 2 binding properties classpath 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");
}
Run Code Online (Sandbox Code Playgroud)

使用 kotlin,这是不可能的:

@PropertySource("classpath:application.properties")
open class WebController {
    @Autowired
    var env: Environment ? = null
}
Run Code Online (Sandbox Code Playgroud)

环境不会引用 PropertySource 文件。我如何在 kotlin 中使用它?

bbu*_*erf 5

对于被注入的字段,kotlin 提供了 Lateinit 关键字。

如果你想从你的配置中读取一个值,spring 为你提供了@Value 注解

@Value("\${my.property.key}")
lateinit var myValue: String
Run Code Online (Sandbox Code Playgroud)

请注意,在 Java 中,您可以用作"${my.property.key}"“路径”,但由于在 kotlin 中具有特殊含义,因此${}您必须使用$\