Don't fail if @Value is not supplied in properties?

Viewed 6400

I import a dependency that have some services with @Value fields. In my spring boot application I don't use these services but I still use some other classes from this dependency, now if I run my application it will fail that it can't resolve the placeholders, e.g.

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'apn.authentication.token.teamId' in value "${apn.authentication.token.teamId}"

So to fix this I have to define the value in my properties. I searched for a setting to let my app not fail on unknown values but I couldn't find a way to do it.

Is there a way to let my spring boot app launch even if there are missing values? Or Should I exclude the classes that I don't use (and how if this is the only option)?

2 Answers

You can set some default values so that if the value does not present it takes the default value

@Value("${apn.authentication.token.teamId:-99}")
private int teamId;

or to set value as null

@Value("${apn.authentication.token.teamId:#{null}}")
private Integer teamId;

You can configure your PropertySourcesPlaceholderConfigurer to not fail on unknown placeholders:

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
    return propertySourcesPlaceholderConfigurer;
}

It will not fail and will not bother to resolve it. In general it is a good practice to fail on unknown properties (they are properties, because your application needs them to function), or to add them default values. If you have configuration that is not critical for your application to function, you can create an additional configuration file and read it at runtime.

Related