简体   繁体   中英

@ConstructorBinding with immutable properties don't work with @Value in Spring Boot Kotlin @ConfigurationProperties

Spring Boot supports Kotlin data classes for @ConfigurationProperties .

@ConstructorBinding
@ConfigurationProperties(prefix = "prefix")
data class AppProperties (
    val something: String
)

But val and @ConstructorBinding has some limitations. You cannot alias one variable to another. Let's say you're running in Kubernetes and want to capture the hostname, which is given by the env var HOSTNAME . The easiest way to do this is to apply @Value("\${HOSTNAME}:)" to a property, but it only works for a mutable property and without constructor binding.

The Spring Boot GitHub issue tracker says:

STOP,, Please ask questions about how to use something. or to understand why something isn't working as you expect it to, on Stack Overflow using the spring-boot tag.

So, is this a known limitation or should I create a ticket for them to fix it?

Edit: Opened https://github.com/spring-projects/spring-boot/issues/25552

@ConfigurationProperties is an alternative to @Value and the two are not designed to be used together. It may work with JavaBean-style binding but that would be by accident rather than by design and it shouldn't be relied upon.

Instead of using @Value to alias something bound via @ConfigurationProperties , it's recommended that you do so via some other means. For example you could use one of the approaches suggested in this answer that Marcos Barbero linked to in the comments on your question. Alternatively, you could take some inspiration from this example in the documentation and use a placeholder in application.properties :

prefix.something=${hostname}

Another option would be to register via META-INF/spring.factories an implementation of EnvironmentPostProcessor that adds a PropertySource to the environment to set up the desired aliasing. For the time being, this is probably the best approach if you want to do something in a reusable library. There's an open issue to remove some of the ceremony that's currently involved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM