我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())
}
应用程序启动没有错误。屏幕截图:
关于java - Spring Boot的@ConfigurationProperties不再起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64073675/