Spring @Value Annotation Example

In this section we will learn about @Value Annotation.

Note 

  • This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level. 
  • It is used to assign default values to variables and method arguments. 
  • We can read spring environment variables as well as system variables using @Value annotation. 
  • Spring @Value annotation also supports SpEL.


Let’s look at some of the examples of using @Value annotation.


1. Set Default/Static Value

We can assign a class member variable with default/static value using @Value annotation.

// Set static string value
@Value("Hi, This is a static message.")
private String staticMessage;

// Set default boolean value
@Value("true")
private boolean booleanValue;

// Set static integer value
@Value("234")
private int integerValue;


2. Get Value from Properties File

@Value can be used to read values from the properties file.


2.1 Get String Value

We know a properties file contains the values in the form of key and value pair.

knf.message=Hi, Greetings from knowledgefactory.net.

Get the value of key knf.message like below.

@Value("${knf.message}")
private String knfMessage;

By default, @Value annotation searches the key in application.properties file in a Spring Boot application. If key is missing or we forgot to define it in properties file that we’ve mentioned in @Value annotation, it will throw BeanCreationException: Error creating bean with name ‘userController‘: Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder ‘knf.message‘ in value "${knf.message}".


2.2 Set Default Value when KEY is Missing

The above exception can be handled by setting the default value when a key is missing or not found in the properties file.

@Value("${user.message: Hi, I'm a default user.}")
private String defaultUserMessage;


2.3 Get List Value

@Value can assign the comma-separated values to a List. Suppose we have a key language.list which holds the names of programming languages separated by a comma in the properties file.

language.list=Java, Kotlin, Go, C

The language.list values can be assigned to list like:

@Value("${language.list}")
private List<String> languageList;


2.4 Get Map Value

We can also set a key value in the form of key and value pairs inside the properties file and assign those values to a Map.

user.details={name: 'Sibin', email: 'sibin@gmail.in'}

It can be assigned to a Map using Spring Expression Language (SpEL) like below.

@Value("#{${user.details}}")
private Map<String, String> userDetails;


3. Accessing Beans

Furthermore, we can use a field value from other beans. Suppose we have a bean named userService with a method message which returns a String "Hello, I'm a User". Then, "Hello, I'm a User" will be assigned to the field.

@Service("userService")
public class UserService {

public String message()
{
return "Hello, I'm a User";
}
}

"Hello, I'm a User" will be assigned to the field like below.

@Value("#{userService.message}")
private String userMessage;


4. Using @Value With Constructor Injection

@Component
@PropertySource("classpath:message.properties")
public class MessageProvider{

private String message;

@Autowired
public MessageProvider(@Value("${message:hello}") String message) {
this.message= message;
}

// getter
}

In the above example, we inject a message directly into our MeesageProvider‘s constructor. 

Note that we also provide a default value in case the property isn't found.


5. Using @Value With Setter Injection

@Component
@PropertySource("classpath:message.properties")
public class ListProvider {

private List<String> values = new ArrayList<>();

@Autowired
public void setValues(@Value("#{'${list}'.split(',')}")
List<String> values) {
this.values.addAll(values);
}

// getter
}

We use the SpEL expression to inject a list of values into the setValues method.


The following example creates a Spring Boot web application which uses @Value annotation.

Project Directory


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-value-annotation-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-value-annotation-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


application.properties

knf.message=Hi, Greetings from knowledgefactory.net.
language.list=Java, Kotlin, Go, C
user.details={name: 'Sibin', email: 'sibin@gmail.in'}


UserService.java

package com.knf.dev.demo;

import org.springframework.stereotype.Service;

@Service("userService")
public class UserService {

public String message()
{
return "Hello, I'm a User";
}
}


Run the application - Application.java

package com.knf.dev.demo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;
import java.util.Map;

@SpringBootApplication
public class Application implements CommandLineRunner {

@Value("Hi, This is a static message.")
private String staticMessage;

@Value("${knf.message}")
private String knfMessage;

@Value("${user.message: Hi, I'm a default user.}")
private String defaultUserMessage;

@Value("${language.list}")
private List<String> languageList;

@Value("#{${user.details}}")
private Map<String, String> userDetails;

@Value("#{userService.message}")
private String userMessage;

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void run(String... args) throws Exception {

System.out.println("Static message= " + staticMessage);
System.out.println("Knowledgefactory message= " + knfMessage);
System.out.println("Default User message= " + defaultUserMessage);
System.out.println("List of all users== " + languageList);
System.out.println("User details= " + userDetails);
System.out.println("User message= " + userMessage);
}
}

Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

Let's run this Spring boot application from either IntelliJ IDEA IDE by right click - Run 'Application.main()'
Or you can use the below maven command to run:

mvn spring-boot:run

Console Output:
Static message= Hi, This is a static message.
Knowledgefactory message= Hi, Greetings from knowledgefactory.net.
Default User message=  Hi, I'm a default user.
List of all users== [Java, Kotlin, Go, C]
User details= {name=Sibin, email=sibin@gmail.in}
User message= Hello, I'm a User


Download Source Code

Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java, Spring Boot Mini Project - Library Management System - Download

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String

Top 5 Java ORM tools - 2024