Spring @Value Annotation Example

Spring @Value Annotation Example show you how to inject properties or system properties into a spring bean using the spring @Value annotation. You can also refer to the previous tutorial that show how to inject properties from a file or multi files using spring xml.

Let’s begin:

Example application.properties file
Here are some properties that we want to inject into a bean.

Read Properties with Spring Property Placeholder
In Spring, the PropertyPlaceholderConfigurer looks up by default not only in the specified properties file but also searchs for Java System properties.
The PropertyPlaceholderConfigurer looks by default not only in the properties file you specify but also searches for Java System properties if it cannot find a property in the specified properties file. If you want you can customize this behavior by setting the system-properties-mode attribute of the property-placeholder with one of the following values:

ENVIRONMENT: indicates placeholders should be resolved against the current Environment and against any local properties. This is the default.
NEVER : this will never check the system properties.
FALLBACK : [default] this will check system properties if no property could be found in the specified properties file.
OVERRIDE : this will check system properties first, if no suitable system property is found then it’ll search in the specified properties file.

For example, we have a spring configuration like below:

Injecting a Local Property / System Property using spring @Value annotation

The spring @Value annotation is easy to use. You cam place it on fields, methods and method/constructor parameters to assign a default value. In this Spring @Value Annotation Example, we are using using the spring expression language to load a property from the application.properties file. Then, we load a system property. Here, we are creating a spring component to read the file.upload.max.size property on Local side and the java.version property on System side.

Testing Spring @Value Annotation

In this Spring @Value Annotation Example, we create a main class to bootstrap Spring and test properties

Run main class above and see the output

That’s all on the Spring @Value Annotation Example tutorial

Spring @Value JavaDoc
Property Placeholder Documentation

Download compelete source code, click link below

spring-value-annotation-example.zip (272 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons