如何在 kotlin 中从 spring application.yaml 获取变量



我的应用程序中有 app.name.yaml

请问我如何访问它,我希望有一个简单的衬里。

@Values似乎不起作用,它只能在我的 restController 中工作。我已经创建了一个配置属性和一个 EnableConfigurationProperties,但没有人会告诉我如何实际从属性中获取值。

class databaseHandler() {
@Value("${app.url}")
private val url: String? = null
fun dave(){
print(url)
} ==Null

==

@Component
@ConfigurationProperties("app")
class appConfig(){
lateinit var url: String
}

@EnableConfigurationProperties(appConfig::class)
class dave(){
fun dave(){
print(appConfig().url)
} ==Lateinit url hasn't been initalized
}

找出问题所在,您还需要初始化子类并将其声明为弹簧组件,例如

@Service
class DatabaseHelper {
@Value("${app.url}")
val url= ""
}

@RestController
@RequestMapping("/")
class GitHubController{
@Autowired
lateinit var databaseHelper : DatabaseHelper 
@GetMapping("")
fun hello() = "hello $databaseHelper.url"
}

假设application.yml具有以下属性:

app-url: www.demo-url.com 

@EnableConfigurationProperties添加到绑定类中,即

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
class appConfig() {
lateinit var url: String
}

@EnableConfigurationProperties此注释用于在 Spring 应用程序中启用@ConfigurationProperties注释的 bean

,此注释

请参考: https://www.baeldung.com/spring-yaml

最新更新