Home > Software design >  Spring boot mandatory environment variable
Spring boot mandatory environment variable

Time:12-25

I have a setting that has no sensible default; I would like my application to refuse to boot if the setting is not supplied. Is there a natural way to achieve this in Spring Boot?

In my application.yml I'm using syntax like this:

    mySetting: "${MY_ENV_VAR}"

If I don't set the MY_ENV_VAR environment variable, the application continues booting and throws a somewhat obscure error.

Is there a recommended way to express my intent that this setting is mandatory?

CodePudding user response:

You can use the @ConfigurationProperties annotation to register a class that carries the mySetting property.

You can then mark this property as @NotNull. See also here.

CodePudding user response:

Normally you have a property in application.yaml which you need somewhere in the application either as a String or Integer or another basic type.

You then later use the property in your application by using @Value inside your component.

So for example the following code is your component that needs this value, you can mark the component as @Validated so the validation annotations are considered and then on the specific property that you need to use the value mySetting you use the @NotBlank. Not blank means not empty string and not null string.

If the validation fails the component initialization will fail and so the application context will not complete and the startup will fail with a relative error pointing at this property.

@Component
@Validated
public class MyComponent {

@NotBlank
@Value(${mySetting})
private String mySetting;

....

}
  • Related