Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin & Spring Boot @ConfigurationProperties

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 variable, foo is constant value and should be initialized during startup and will not change in the future.

like image 265
Sonique Avatar asked Oct 20 '22 00:10

Sonique


People also ask

What is the Kotlin used for?

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.

Is Java better than Kotlin?

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.

Is Kotlin same as C++?

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.

Is Kotlin better than Python?

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.


2 Answers

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")
}
like image 60
Dmitry Kaltovich Avatar answered Oct 22 '22 14:10

Dmitry Kaltovich


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.

like image 53
Ray Hunter Avatar answered Oct 22 '22 13:10

Ray Hunter