Add extension for PropertyResolver#getProperty(String, Class<T>, T)
Allows Kotlin caller to get a non-nullable property, using a default value when the property is not set. A method already exists on PropertyResolver which does this, but takes a Class parameter. The extension method can eliminate the parameter via reified type, similar to the other extension methods which exist already. Closes gh-31523
This commit is contained in:
committed by
Sébastien Deleuze
parent
34e5512ff6
commit
8c77e398b6
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2002-2019 the original author or authors.
|
||||
* Copyright 2002-2023 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -42,6 +42,16 @@ operator fun PropertyResolver.get(key: String) : String? = getProperty(key)
|
||||
inline fun <reified T> PropertyResolver.getProperty(key: String) : T? =
|
||||
getProperty(key, T::class.java)
|
||||
|
||||
/**
|
||||
* Extension for [PropertyResolver.getProperty] providing a `getProperty<Foo>(...)`
|
||||
* variant returning a non-nullable `Foo` with a default value.
|
||||
*
|
||||
* @author John Burns
|
||||
* @since 6.1
|
||||
*/
|
||||
inline fun <reified T : Any> PropertyResolver.getProperty(key: String, default: T) : T =
|
||||
getProperty(key, T::class.java, default)
|
||||
|
||||
/**
|
||||
* Extension for [PropertyResolver.getRequiredProperty] providing a
|
||||
* `getRequiredProperty<Foo>(...)` variant.
|
||||
|
||||
@@ -19,6 +19,7 @@ package org.springframework.core.env
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.verify
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
/**
|
||||
@@ -44,6 +45,13 @@ class PropertyResolverExtensionsKotlinTests {
|
||||
verify { propertyResolver.getProperty("name", String::class.java) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getProperty with default extension`() {
|
||||
every { propertyResolver.getProperty("name", String::class.java, "default") } returns "default"
|
||||
assertThat(propertyResolver.getProperty<String>("name", "default")).isEqualTo("default")
|
||||
verify { propertyResolver.getProperty("name", String::class.java, "default") }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getRequiredProperty extension`() {
|
||||
every { propertyResolver.getRequiredProperty("name", String::class.java) } returns "foo"
|
||||
|
||||
Reference in New Issue
Block a user