Skip to content

Instantly share code, notes, and snippets.

@timsmelik
Created December 14, 2022 14:05
Show Gist options
  • Save timsmelik/fcae7a6c7de6862f51237261147dd007 to your computer and use it in GitHub Desktop.
Save timsmelik/fcae7a6c7de6862f51237261147dd007 to your computer and use it in GitHub Desktop.
Kotlin + Spring: ConfigurationProperties data classes

Kotlin + Spring: ConfigurationProperties data classes

Create the application.properties or application.yml file

email:
  from: myemail@mydomain.com
  to: theiremail@theirdomain.com

Create the data class

@ConstructorBinding
@ConfigurationProperties(prefix = "email")
data class EmailProperties(
  val from: String,
  val to: String
)

The data class has to be annoted with two annotations:

  1. @ConfigurationProperties to bind the properties in our properties or yml file to this class.
  2. @ConstructorBinding because we're using a data class. By default, Spring uses the default constructor and setters to instantiate the class annotated by @ConfigurationProperties, this obviously doesn't work with data classes.

Add configuration for detecting @ConfigurationProperties annotated classes

We need to add some configuration to an existing or new class annotated with @Configuration. In this example, we will use a new class.

@Configuration
@ConfigurationPropertiesScan
class EmailConfiguration

We need only a single annotation: @ConfigurationPropertiesScan. This will enable scanning for any @ConfigurationProperties annotated classes in the current package and any sub-packages.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment