How to properly initialize ConfigurationProperties in Spring Boot with Kotlin?
Currently I do like in the example below:
@ConfigurationProperties("app")
class Config {
var foo: String? = null
}
But it looks pretty ugly and actually foo
is not a var
iable, foo is constant val
ue and should be initialized during startup and will not change in the future.
What is Kotlin? Kotlin is an open-source statically typed programming language that targets the JVM, Android, JavaScript and Native. It's developed by JetBrains.
Java has the power of using third-party code to make writing codes easier. Java is fairly simple to handle and removing bugs from it becomes easier when compared to Kotlin. The standards of safety in Java are of higher quality than Kotlin.
What is Kotlin? Statically typed Programming Language targeting JVM and JavaScript. Kotlin is a statically typed programming language for the JVM, Android and the browser, 100% interoperable with Java. C++ and Kotlin can be categorized as "Languages" tools.
Both Python and Kotlin maybe used in backend development, but in mobile development (Android), Kotlin has a significant advantage over Python. Kotlin has Google's backing; it's faster to compile; and it has built-in null safety support. All java libraries are compatible with Kotlin.
With new Spring Boot 2.2 you can do like so:
@ConstructorBinding
@ConfigurationProperties(prefix = "swagger")
data class SwaggerProp(
val title: String, val description: String, val version: String
)
And don't forget to include this in your dependencies in build.gradle.kts
:
dependencies {
annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
}
Here is how I have it working with my application.yml file.
myconfig:
my-host: ssl://example.com
my-port: 23894
my-user: user
my-pass: pass
Here is the kotlin file:
@Configuration
@ConfigurationProperties(prefix = "myconfig")
class MqttProperties {
lateinit var myHost: String
lateinit var myPort: String
lateinit var myUser: String
lateinit var myPass: String
}
This worked great for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With