Home » Spring Boot » Spring @Value Annotation Example

Spring @Value Annotation Example

Spring Boot @Value annotation injects property values from application.properties file into spring bean.@Value annotation is used to assign values to variables and method arguments. It was introduced in Spring’s version 3.0.@Value annotation is widely used to get values from the properties file in a Spring Boot application.

1. Set Default/Static Value :

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

// Set static string value
@Value("message")
private String stringValue;
// Set static integer value
@Value("101")
private int integerValue;
// Set default boolean value
@Value("true")
private boolean booleanValue;

2. Reading Values from Properties File

@Value annotation is used to read values from the properties file.

(a) Getting String Value

As you aware a properties file contains the values in the form of "key" and "value" pair.

user.first.name=mukesh
user.last.name=kumar

To get the value of key and set it to the class member variable, we need to use below syntax.

@Value("${property_name}")

So to get user.first.name and user.last.name we need to use below code in java class.

@Value("${user.first.name}")
private String firstName;

@Value("${user.last.name}")
private String lastName;					

What happens when the key is missing or we forgot to define it in properties file that we’ve mentioned in @Value annotation?

Answer for this is Application run will failed with org.springframework.beans.factory .BeanCreationException. you can see the stack trace of this error in the console.


(b) 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.

The syntax is almost the same as mentioned above, the only change is we have to set our default message followed by a colon (:) just after the key.

@Value("${user.first.name:Mukesh}")
private String firstName;

@Value("${user.last.name:Kumar}")
private String lastName;					

(c) Getting List Values

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

emp.list=Amit, Nitish, John, Ravi			

The emp.list values can be assigned to list in a java class as shown below.

@Value("${emp.list}")
private List empList;

(c) Getting 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.


emp.details={firstName: 'Mukesg', lastName: 'Kumar', company: 'javawebtutor.com'}

It can be assigned to a Map using Spring Expression Language (SpEL). In this, we have to surround all the above syntax by a HASH (#) symbol as shown below.

@Value("#{${emp.details}}")
private Map empDetails;

Injecting Values In Methods:

Apart from the field-based injection, we can also use @Value annotation over a method:

@Value("${user.first.name}")
public void setUserName(String userName) {
    this.userName = userName;
}			

If we use @Value annotation over a method, all of its arguments will get mapped to the same value.

If we want to inject different parameters to different arguments, we can use @Value annotation along with method arguments:


public void setUserDetails(@Value("${user.first.name}")String userName,
  @Value("${user.address}") String address) {
    this.userName = userName;
    this.address = address;
}						

Lets jump to the actual piece of coding and build a running spring boot application.

Directory Structure of Project :

Spring Boot Hello World


application.properties

emp.firstname=Mukesh
emp.lastname=Kumar
emp.list=Mukesh, Amit, Santosh, Ravi
emp.details={firstName: 'Mukesh', lastName: 'Kumar', company: 'javawebtutor.com'}

EmployeeController.java


package com.jwt.spring.boot.demo.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {

	@Value("Hi, welcome to javawebtutor...")
	private String staticMessage;

	@Value("${emp.message.default: This is default message.}")
	private String defaultEmpMessage;

	@Value("${emp.firstname}")
	private String firstName;

	@Value("${emp.lastname}")
	private String lastName;

	@Value("${emp.list}")
	private List empList;

	@Value("#{${emp.details}}")
	private Map empDetails;

	@GetMapping("/employee")
	public String getEmployeeInfo() {
		return toString();
	}

	@Override
	public String toString() {
		return "EmployeeController [staticMessage=" + staticMessage + ", defaultEmpMessage=" + defaultEmpMessage
				+ ", firstName=" + firstName + ", lastName=" + lastName + ", empList=" + empList + ", empDetails="
				+ empDetails + "]";
	}

}

Run and Test the application

To test the application, start the Spring Boot application by executing the below main class and http://localhost:8080/employee API in your favorite web browser:


package com.jwt.spring.boot.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootValueDemoApplication {

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

}

Output

Spring Boot Hello World


You can get the whole code used in this post from our GitHub repository:

GitHub

Previous Next Article