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

  • 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 name property in the HelloWorld object equal to the value of the property name in the configuration.properties file then I will do as following:

  • 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 HelloWorld bean in Spring container:

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

Here, I have declared @Value annotation with the value is $ {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 property name does not exist, we can substitute the default value by declaring @Value annotation as follows:

Result:

Using properties in Spring with @Value annotation

Using properties in Spring with @Value annotation
Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
6Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.