Using properties in Spring with @Value annotation

In this tutorial, I would like to introduce to you all how to use properties in Spring with @Value annotation.

First of all, we need a Maven project for example:

Using properties in Spring with @Value annotation

I will use Java 17 for this example:

Spring framework dependency:

HelloWorld class:

Application class:

configuration.properties

spring.xml




To use properties with @Value annotation, we need to declare bean in Spring using annotations such as @Component, @Service, @Repository, @Controller, …

In this example, I want to declare the HelloWorld object in the Spring container and use the @Value annotation to assign the value of the name property in the HelloWorld object equal to the value of the property name in the configuration.properties file then I will do as follows:

First, I will declare tag context:component-scan in spring.xml file to enable auto component scan in Spring for package com.huongdanjava.springvalueanntation:

After that, I will declare @Component in class HelloWorld to initialize the HelloWorld bean in the Spring container:

Finally, I will use @Value annotation to ingest the value of the property name in configuration.properties into the name property in the HelloWorld object as below:

Here, I have declared @Value annotation with the value $ {property_name}.

Result:

Using properties in Spring with @Value annotation



In case the property name does not exist, the following error is encountered when running:

To avoid this error, in case the property name does not exist, we can substitute the default value by declaring the @Value annotation as follows:

Result:

Using properties in Spring with @Value annotation

1/5 - (1 vote)

Add Comment