I am trying different attempts to get the value from the yaml file, but no matter what I try, it stays null.
application.yml file
demo-control:
environment: ${ENVIRONMENT:prod}
managedRegions: ${MANAGED_REGIONS:us-east-1}
Component Class Attempt:1
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.stereotype.Component
@Component
class AppProperties(@Value("\${demo-control.managedRegions}") private val managedRegions: String)
Component Class Attempt 2
@Component
class AppProperties {
@Value("\${demo-control.managedRegions}")
lateinit var managedRegions: String
}
class that I would like to use the value
class AwsProvider(
private val creds: AwsCredentials,
@Value("\${demo-control.managedRegions}")
private val managedRegions: String? = null // Attempt1
) : CloudProvider {
Attempt1
@Value("\${demo-control.managedRegions}")
private val managedRegions: String? = null
Attempt2
@Value("\${demo-control.managedRegions}")
lateinit var region:String
Using the @Value
annotation is a straightforward approach to get config values from application.yml
, similar to what you have tried above.
I have used the annotation to inject the config value to a Controller
in a sample Spring Boot app which works as expected. The relevant code is shared below:
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
...
@RestController
@RequestMapping("v1/orders")
class OrdersController {
@Value("\${demo-control.managedRegions}")
private lateinit var managedRegions: String
private final val log = LoggerFactory.getLogger(this.javaClass)
@GetMapping(produces = [MediaType.APPLICATION_JSON_VALUE])
fun getOrders(): List<OrderDto> {
log.info("demo-control.managedRegions: $managedRegions")
...
}
And here is the log that prints the demo-control.managedRegions
config value:
2024-10-31T16:10:00.504+05:30 INFO 1834 --- [nio-8080-exec-3] c.d.s.api.OrdersController: demo-control.managedRegions: us-east-1
The application.yml
file:
demo-control:
environment: ${ENVIRONMENT:prod}
managedRegions: ${MANAGED_REGIONS:us-east-1}
The Spring Boot application:
@SpringBootApplication
class SpringDemoApplication
fun main(args: Array<String>) {
runApplication<SpringDemoApplication>(*args)
}
The build.gradle
with Spring Boot plugins and dependency:
plugins {
id("org.springframework.boot")
id("io.spring.dependency-management")
kotlin("jvm")
kotlin("plugin.spring")
}
implementation("org.springframework.boot:spring-boot-starter-web")