Spring @Value Annotation


Spring @Value annotation is used to inject values into variables and method arguments. We can either read spring environment variables or system variables. It also supports SpEL.

In this quick tutorial, we’ll explore how to work with Spring @Value annotation.


Let’s start by first defining a few properties in our app.properties file:

products.count={P1: '3', P2: '10', P3: '5'}

These are the properties we’ll use for examples throughout this tutorial.

Also, let’s quickly define our AppConfiguration class:

public class AppConfiguration {


Spring @Value – Basics:

We can assign a default value to a class property with @Value annotation:

private int value;

@Value("Hello World")
private String msg;

Note that it accepts only a String argument but the passed-in value gets converted to an appropriate type during value-injection.

Reading Spring Environment Variables:

We can use @Value annotation to read a Spring environment variable:

private String userFirstName;

We can also read a list of values:

private String[] userPreferences;

Let’s now try to read a map of values ‘products.count’ using @Value annotation:

private Map<String, Integer> productsCount;

To get a value of a specific key from the map, we’ll use:

private Integer p1Count;

Reading System Variables:

With Spring @Value, we can also read the system variables, either directly:

private String javaHome;

Or using SpEL:

private String javaHome;

Assigning Default Value:

What if we wish to assign a default value in case of a missing property? Yes, we can do it using Spring @Value annotation’s default construct:

private int stockCount;

Here, the default value of 30 will be assigned to stockCount only if the property ‘user.stocks’┬áis missing from the property file.

We can also assign a default value when working with SpEL:

@Value("#{systemProperties['abc'] ?: 'default value'}")
private String unknownSystemProperty;

Injecting Values In Methods:

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

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;


In this tutorial, we explored different ways in which we can use @Value annotation to inject property values. We can use @Value annotation either with a field or a method.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *