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

标签 java spring spring-boot kotlin

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/

相关文章:

java - 在外部缓存中缓存分离的 Hibernate 实体

java - 什么是 spring boot 版本控制约定?

spring - logback找不到maven的属性project.build.directory

java - 在 Spring Data JPA 中创建分页

java - java中的外部化

java - 将具有多个值的 map 转换为树?

spring - 当找到多个匹配的bean时,Spring如何按名称 Autowiring ?

java - JPA:如何设置历史实体的 key

java - 我需要创建一百个 getter 和 setter 吗?

java - Spring Boot 验证信息未显示在 Swagger UI 中