gpt4 book ai didi

java - Spring Boot的@ConfigurationProperties不再起作用

转载 作者:行者123 更新时间:2023-12-02 13:40:25 26 4
gpt4 key购买 nike

have一个简单的Spring Boot 2.3.4.RELEASE应用程序(使用Kotlin 1.3.72)。我在Gradle Kotlin DSL中配置了所有插件:

plugins {
id("org.gradle.application")
id("org.gradle.idea")
id("org.jetbrains.kotlin.jvm")
id("org.jetbrains.kotlin.plugin.spring")
id("org.springframework.boot")
}
我正在尝试从 application.yml文件中读取一些设置/值:
application:
server:
port: ${MOCKSERVER_PORT:1080}
...
我使用 @ConfigurationProperties@ConstructorBinding,但是无论我如何移动配置文件,我总会得到:
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in org.acme.config.MockServerConfig$ApplicationProps required a bean of type 'org.acme.config.MockServerConfig$ApplicationProps$ServerProps' that could not be found.


Action:

Consider defining a bean of type 'org.acme.config.MockServerConfig$ApplicationProps$ServerProps' in your configuration.
这是应用程序和我拥有的配置文件的相关部分:
@SpringBootApplication
@Import(MockServerConfig::class)
@EntityScan(basePackages = ["org.acme.domain"])
class Application

fun main(args: Array<String>) {
runApplication<Application>(*args)
}
@Configuration
@EnableConfigurationProperties(MockServerConfig.ApplicationProps::class)
class MockServerConfig(private val application: ApplicationProps) {
@Bean
fun mockServerClient(): MockServerClient = ClientAndServer.startClientAndServer(application.server.port)

@ConstructorBinding
@ConfigurationProperties(prefix = "application")
data class ApplicationProps(val server: ServerProps) {
data class ServerProps(val port: Int)
}
}
我知道错误消息说了什么,但是我不能将 @Component(或任何其他构造型)用于 ServerProps。我会得到另一波错误。
任何Boot黑客都能对此有所启发吗?

I've read tons of questions and blog posts around the subject, but still I can't work around the issue.

最佳答案

我面临着同样的问题。
您试图从1080在MockServer中设置端口application.yml
您可以使用Spring的Environment类读取所有属性。
我想出了以下方法:

package org.acme.config

import org.mockserver.client.MockServerClient
import org.mockserver.integration.ClientAndServer
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.env.Environment

@Configuration
class MockServerConfig {

@Autowired
private lateinit var env: Environment

@Bean
fun mockServerClient(): MockServerClient = ClientAndServer.startClientAndServer(env.getProperty("application.server.port")?.toInt())

}
应用程序启动没有错误。
屏幕截图:
enter image description here

关于java - Spring Boot的@ConfigurationProperties不再起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64073675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com