Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev. The current series is about building a Kanban API with Spring.

Basic properties handling

14.03.2018 by Jens in Spring Boot | Newsletter

Spring makes it easy to inject configuration values from outside the code. Simple use the @Value annotation on a field and define the name of the property like:

private String myProp;

${} indicates a statement using the Spring Expression Language (SpEL). It will lookup for a property in the PropertySource. This one usually, will check include properties from property files, env variables, and system variables.

It is auto-configured in Spring Boot and will include the application.properties and _application.yml_and of course env and system variables. If we define our property at any of these places, it will be found. If not, an Exception will be thrown.

We can ├╝revent that by adding a default value. We do have two alternative ways.

First, we could just declare it in the application.properties with the default value. In case we want to override it, we just define it as an env, system or program variable. Those win over the property file.

Second, we could define the default value already in the @Value annotation by adding a _ :_ followed by the default value as a suffix to the property name like:

private String myProp;

In this case, Spring will use the default value, if it did not find any declaration of it in the PropertySource.

comments powered by Disqus