Spring Boot - Detect and terminate if property not set?

To throw a friendly exceptions just put a default null value in property, check and throw a exception in afterProperty method.

@Component
public static class ConfigurationGuard implements InitializingBean {

@Value("${my.home:#{null}}")
private String myHomeValue;

public void afterPropertiesSet() {
    if (this.myHomeValue == null or this.myHomeValue.equals("${my.home}") {
          throw new IllegalArgumentException("${my.home} must be configured");
    }
 }
}

Create a bean with a simple @Value(${my.home}) annotated field. - Then Spring will try to inject that value and will fail and therefore stop when the value is not there.


Just @Value(${my.home}) private String myHomeValue; is enough for normal (not Boot) Spring applications for sure! But I do not know whether Boot has some other configuration to handle missing values: If there is an other failure management than you could check that value in an PostCreation method.

@Component
public static class ConfigurationGuard implements InitializingBean {

   @Value(${my.home})
   private String myHomeValue;

   /**
    * ONLY needed if there is some crude default handling for missing values!!!!
    *
    * So try it first without this method (and without implements InitializingBean)
    */
   public void afterPropertiesSet() {
      if (this.myHomeValue == null or this.myHomeValue.equals("${my.home}") {
          throw new IllegalArgumentException("${my.home} must be configured");
      }
   }

}