Additional environment variables with @Value in Spring

Using @Value for a nonexistent environment variable will raise an IllegalArgumentException: the placeholder 'ENV_VAR' could not be resolved to the string value "$ {ENV_VAR}".

For example:

@Autowired
public SomeClass(@Value("{ENV_VAR}") final String value) { }

How to do this optional?

+4
source share
1 answer

Use the default and Optional class (in JDK8).

@Autowired
public SomeClass(@Value("{ENV_VAR:#{null}}") final Optional<String> value) {
    value.ifPresent(/* do something */);
}
+3
source

Source: https://habr.com/ru/post/1607221/