<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>@ConfigurationProperties Archives - Codersee blog- Kotlin on the backend</title>
	<atom:link href="https://blog.codersee.com/tag/configurationproperties/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Kotlin &#38; Backend Tutorials - Learn Through Practice.</description>
	<lastBuildDate>Wed, 16 Apr 2025 04:49:52 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://blog.codersee.com/wp-content/uploads/2025/04/cropped-codersee_logo_circle_2-32x32.png</url>
	<title>@ConfigurationProperties Archives - Codersee blog- Kotlin on the backend</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Fail Spring Boot App on Missing Environment Variables</title>
		<link>https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/</link>
					<comments>https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/#respond</comments>
		
		<dc:creator><![CDATA[Piotr]]></dc:creator>
		<pubDate>Sat, 16 Sep 2023 05:43:54 +0000</pubDate>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[@ConfigurationProperties]]></category>
		<category><![CDATA[Configuration]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<guid isPermaLink="false">https://codersee.com/?p=9007594</guid>

					<description><![CDATA[<p>In this article we will learn 4 ways to prevent Spring Boot app from starting when environment variable is missing. </p>
<p>The post <a href="https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/">Fail Spring Boot App on Missing Environment Variables</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Hello and welcome to my blog🙂 If you&#8217;ve been working with <strong>@ConfigurationProperties</strong> and <strong>environment variables</strong> in Spring Boot, then you probably saw that by default, Spring Boot does not fail when the value is missing.</p>



<p>In this article, I will show you <strong>four ideas</strong> on how to solve this issue. </p>



<p>Please keep in mind that all of them are workarounds, and if you came up with something even better, then do not forget to share in the comments🙂</p>



<h2 class="wp-block-heading" id="h-video-tutorial">Video Tutorial</h2>



<p>If you prefer <strong>video content</strong>, then check out my video:</p>



<div style="text-align: center; width: 90%; margin-left: 5%;">
<p></p></div>


<a href="https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/"><img decoding="async" src="https://blog.codersee.com/wp-content/plugins/wp-youtube-lyte/lyteCache.php?origThumbUrl=%2F%2Fi.ytimg.com%2Fvi%2F6hAGbp8I5ow%2Fhqdefault.jpg" alt="YouTube Video"></a><br /><br /></p>



<p>If you find this content useful,<strong> please leave a subscription&nbsp;</strong> 😉</p>



<h2 class="wp-block-heading" id="h-problem">Problem</h2>



<p>To be on the same page, let&#8217;s take a quick look at a simple Spring Boot configuration with @ConfigurationProperties.<br><br>Firstly, let&#8217;s navigate to the <code>application.yaml</code> file: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">example:
  some-property: ${SOME_VARIABLE}</pre>



<p>As we can see, we defined a new property inside our config file for which the value should be set from the environment variable named <code>SOME_VARIABLE</code>.<br><br>Following, let&#8217;s introduce the <em>@ConfigurationProperties</em> class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@ConfigurationProperties(prefix = "example")
data class ExampleConfigurationProperties(
  val someProperty: String
)</pre>



<p>With this code, we expect that Spring Framework will read all properties defined in the configuration file and inject values into the matching properties.<br></p>



<p></p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>
<cite>Note: Spring recognizes the kebab case (some-property) and matches it with the property using camel case (someProperty)</cite></blockquote>



<p><br>After that, we need to explicitly inform Spring about our configuration properties class: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Configuration
@EnableConfigurationProperties(ExampleConfigurationProperties::class)
class Config</pre>



<p>Lastly, we must add a class, which injects the <em>ExampleConfigurationProperties</em> and prints out the value of <em>someProperty:</em></p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">@Component
class SomeComponent(
  private val properties: ExampleConfigurationProperties
) {

  @PostConstruct
  fun init() {
    println(properties.someProperty)
  }

}</pre>



<p>Finally, when we run our application <strong>without the <em>SOME_VARIABLE</em> environment variable missing</strong>,<strong> </strong>we will see the following output: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">${SOME_VARIABLE}</pre>



<p>A bit counterintuitive, right? <br><br>It would seem pretty obvious, that if we declare <em>someProperty </em>as a non-nullable String and environment variable is missing, our Spring Boot app should fail to start. <br><br>Unfortunately, that&#8217;s not the case when using <em>@ConfigurationProperties</em> and Spring will default the String value to the name of placeholder. <br><br>Moreover, at the moment of writing, there is no built-in way we could enforce that. </p>



<h2 class="wp-block-heading" id="h-solution-with-spring-validation">Solution With Spring Validation</h2>



<p>As a first solution (or rather workaround), let&#8217;s add the <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation" target="_blank" rel="noreferrer noopener">spring-boot-starter-validation</a> to our project:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">implementation("org.springframework.boot:spring-boot-starter-validation")</pre>



<p>Nextly, let&#8217;s instruct Spring that it should default to the blank String value whenever our environment variable is missing:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="yaml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">example:
  some-property: ${SOME_VARIABLE:}</pre>



<p>After that let&#8217;s modify our configuration properties class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import jakarta.validation.constraints.NotBlank
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.validation.annotation.Validated

@ConfigurationProperties(prefix = "example")
@Validated
data class ExampleConfigurationProperties(
  @field:NotBlank val someProperty: String
)</pre>



<p>As we can see, with a combination of <em>@Validated</em> and <em>@NotBlank</em>, we ask Spring Framework to check if the value is <strong>not null</strong> and contains at least <strong>one non-whitespace character</strong>.<br> </p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p></p>
<cite>Note: in Kotlin, we must use the @field: to annotate Java field. <br><br>If you would like to learn this, and many more then check out my <a href="https://blog.codersee.com/kotlin-handbook-learn-through-practice-course/">Kotlin course</a>.</cite></blockquote>



<p><br>Finally, when we try to run our application, we will see the following:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'example' to com.codersee.properties.ExampleConfigurationProperties failed:

    Property: example.someProperty
    Value: ""
    Origin: class path resource [application.yaml] - 2:18
    Reason: must not be blank


Action:

Update your application's configuration


Process finished with exit code 1</pre>



<p>And maybe this solution is nott ideal, but it does its job. </p>



<p>And it is neat. Not only does the application not start, but also whenever the environment variable for our @ConfigurationProperties is missing, we will see a meaningful message that will speed up the debugging process.</p>



<h2 class="wp-block-heading" id="h-custom-applicationrunner-idea">Custom ApplicationRunner Idea</h2>



<p>Another solution for our problem does not require any additional dependencies added to our project. </p>



<p>Let&#8217;s take a look at the following implementation of <em>ApplicationRunner</em>: </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component

@Component
class MyApplicationRunner : ApplicationRunner {

  companion object {
    private val requiredVariables = setOf(
      "SOME_VARIABLE"
    )
  }

  override fun run(args: ApplicationArguments) {
    requiredVariables.forEach {
      System.getenv(it)
        ?: throw MissingEnvVariableException(it)
    }
  }

}

class MissingEnvVariableException(variableName: String) :
  RuntimeException("Application failed to start. Missing environment variable: $variableName")
</pre>



<p>This time, we introduce our set of required environment variables and check if they are present.</p>



<p>Whenever it&#8217;s missing, we throw the <em>MissingEnvVariableException </em>and prevent the app from starting:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">java.lang.IllegalStateException: Failed to execute ApplicationRunner
	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:765) ~[spring-boot-3.1.3.jar:3.1.3]
	at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:752) ~[spring-boot-3.1.3.jar:3.1.3]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) ~[spring-boot-3.1.3.jar:3.1.3]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-3.1.3.jar:3.1.3]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-3.1.3.jar:3.1.3]
	at com.codersee.properties.PropertiesApplicationKt.main(PropertiesApplication.kt:13) ~[main/:na]
Caused by: com.codersee.properties.MissingEnvVariableException: Application failed to start. Missing environment variable: SOME_VARIABLE
	at com.codersee.properties.MyApplicationRunner.run(MyApplicationRunner.kt:19) ~[main/:na]
	at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:762) ~[spring-boot-3.1.3.jar:3.1.3]
	... 5 common frames omitted


Process finished with exit code 1</pre>



<p>This solution gives us a bit more control and allows us to customize the behavior better. </p>



<p>Would we like to log an error, or maybe send an alert request? No problem. With a few lines of code, we can easily achieve that. </p>



<p>Nevertheless, with this approach, we introduce a new, separate place in the code we need to remember every time we want to add a new environment variable. And this might be easily forgotten in bigger projects.</p>



<h2 class="wp-block-heading" id="h-fix-with-conditional">Fix With @Conditional </h2>



<p>As the next step, let&#8217;s take a look at the approach with <em>@Conditional</em> annotation, which slightly reduces the chance of forgetting about additional checks. </p>



<p>Firstly, let&#8217;s add a new class called <em>RequiredEnvVariablesCondition</em>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class RequiredEnvVariablesCondition : Condition {

  private val logger: Logger = LogManager.getLogger(this::class.java)

  companion object {
    private val requiredVariables = setOf(
      "SOME_VARIABLE"
    )
  }

  override fun matches(context: ConditionContext, metadata: AnnotatedTypeMetadata): Boolean {
    val isEnvVariableMissing = requiredVariables
      .any { envVariableName ->
        val isMissing = System.getenv(envVariableName) == null

        if (isMissing)
          logger.error("Variable $envVariableName is missing!")

        isMissing
      }

    return !isEnvVariableMissing
  }

}</pre>



<p>As we can see, this logic is pretty similar to what we&#8217;ve done previously. </p>



<p>Every time the environment variable is missing, we log an error message and return false from the overridden <em>matches</em> function. </p>



<p>So with that done, we can annotate our config class with <em>@Conditional</em>:  </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Conditional
import org.springframework.context.annotation.Configuration

@Configuration
@EnableConfigurationProperties(ExampleConfigurationProperties::class)
@Conditional(RequiredEnvVariablesCondition::class)
class Config</pre>



<p>This time, we will get the following output if we try to run the app without passing the environment variable:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">2023-09-14T07:20:58.813+02:00 ERROR 16188 --- [           main] c.c.p.RequiredEnvVariablesCondition      : Variable SOME_VARIABLE is missing!

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.codersee.properties.SomeComponent required a bean of type 'com.codersee.properties.ExampleConfigurationProperties' that could not be found.


Action:

Consider defining a bean of type 'com.codersee.properties.ExampleConfigurationProperties' in your configuration.


Process finished with exit code 1</pre>



<h2 class="wp-block-heading" id="h-bonus-use-value-instead">(Bonus) Use @Value Instead</h2>



<p>There&#8217;s no doubt that <em>@ConfigurationProperties</em> helps us write cleaner code and better organize configuration in our codebase. Moreover, we can effortlessly add new values to the project with this approach. </p>



<p>However, in some cases, we should consider using @Value annotation instead:   </p>



<pre class="EnlighterJSRAW" data-enlighter-language="kotlin" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.codersee.properties

import jakarta.annotation.PostConstruct
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Component

@Component
class SomeComponent(
  @Value("\${example.some-property}") private val someProperty: String
) {

  @PostConstruct
  fun init() {
    println(someProperty)
  }
}</pre>



<p>This time, we can completely get rid of <em>@Configuration</em> and <em>@ConfigurationProperties</em> classes.</p>



<p>Instead of injecting a whole configuration object, we focus on the desired config value. </p>



<p>And whenever it&#8217;s missing, we get the following output out of the box:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-09-14T07:16:43.532+02:00 ERROR 18412 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someComponent' defined in file: Unexpected exception during bean creation
...
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'SOME_VARIABLE' in value "${SOME_VARIABLE}"
...
Process finished with exit code 1</pre>



<p>As we can see, our Spring Boot app won&#8217;t start if the environment variable is missing and we will get a meaningful message. </p>



<p>But again, we should use <em>@Value</em> wisely and most of the time <em>@ConfigurationProperties</em> can be a better approach. </p>



<h2 class="wp-block-heading" id="h-summary">Summary </h2>



<p>And that&#8217;s all for this article on how to fail a Spring Boot app on missing environment variables. </p>



<p>As I mentioned in the beginning- these are just a few ideas that came to my mind. If you figure out some other way, then please share them in the comments section below. </p>



<p>As always, you can find the source code in this GitHub repository. </p>



<p>Thank you for reading, and see you next time! 🙂 </p>
<p>The post <a href="https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/">Fail Spring Boot App on Missing Environment Variables</a> appeared first on <a href="https://blog.codersee.com">Codersee blog- Kotlin on the backend</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.codersee.com/fail-spring-boot-app-on-missing-environment-variables/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 

Served from: blog.codersee.com @ 2026-02-25 18:38:46 by W3 Total Cache
-->