Introduction to Spring @Value Annotation

The @Value annotation used at the field or method/constructor parameter level that indicates a default value expression for the annotated element.

Typically used for expression-driven or property-driven dependency injection. Also supported for dynamic resolution of handler method arguments — for example, in Spring MVC.

A common use case is to inject values using #{systemProperties.myProp} style SpEL (Spring Expression Language) expressions. Alternatively, values may be injected using ${my.app.myProp} style property placeholders.

The processing of the @Value annotation is performed by a BeanPostProcessor which in turn means that you cannot use @Value within BeanPostProcessor or BeanFactoryPostProcessor types.

the @Value annotaion is in Spring since Spring 3.0

In this tutorial we will see how to use @Value annotation in the following cases.

1). Using ${...} with @Value
2). Using #{...} with @Value
3). @Value with @Component
4). @Value Constructor Injection
5). @Value with Enum
6). @Value JUnit Test
7). @Value Default Value
8). @Value Boolean Value
9). @Value Integer Value
10).@Value with Array
11).@Value with List
12. @Value with Map
13. Using @Value with @ImportResource

1). Using ${...} with @Value

${...} is used as property placeholder.

MyAppConfig.java

@Configuration @PropertySource("classpath:application.properties") public class MyAppConfig { @Value("${user.defalult.creator}") private String creator; }

2). Using #{...} with @Value

#{...} is a SpEL syntax. It handles property placeholders.

@Value("#{systemProperties['myapp.home']}") private String appHome;

systemProperties provides system property values such as file.separator, java.home, os.name etc. In the above code @Value will inject the value of java.home to mySystemVal field.

4). @Value Constructor Injection

@Value can be used with constructor parameter and then in constructor injection, Spring will inject value specified by @Value annotation.

We have values in the property files as

application.properties

college.name=Modern College,Pune college.grade=A+

and in our service class we have
@Service public class CollegeService { private String name; private String grade; public CompanyService(@Value("${college.name}") String name, @Value("${college.grade}") String grade) { this.name = name; this.grade = grade; } }

and for the default values,if the values is not present in the property file.

@Service public class CollegeService { private String name; private String grade; public CompanyService(@Value("${college.name:Modern College,Pune}") String name, @Value("${college.grade:A+}") String grade) { this.name = name; this.grade = grade; } }

5). @Value with Enum

We can use enum with @Value annotation. A field or constructor parameter can be injected with enum value using @Value annotation.

suppose we have enum class as

Designation.java public enum Role { ADMIN, ACCOUNTANT, SALESLEAD, MANAGER, ITOFFICIER, CASHIER; }

Suppose we have a property file with following property.

application.properties

user.role= ITOFFICIER

Now inject value to enum field as following.

UserService.java

@Component public class UserService { @Value("${user.role}") protected Role role; }

6). @Value JUnit Test

for loading the values from proprty file for the junit test cases is similar to above cases.

We have to provide name of the property file we have to load and we done.

import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = AppConfig.class) @TestPropertySource("/test.properties") public class MyAppTest { @Value("${user.failedAttempts}") private String failedAttempts; @Value("${user.creator}") private String creator; @Test public void test1() throws Exception { assertTrue("3".equals(failedAttempts)); } @Test public void test2() throws Exception { assertTrue("Admin".equals(creator)); } }

7). Spring @Value – Default Value

We can assign the default value to the variables usring Spring @Value annotation.

We can assign any default value to the variable.

@Value("Admin") private String creator; @Value("10") private int maxResults;

8). @Value for Boolean Value

The default value for Boolean and In

@Value("true") private boolean isActive;

the boolean value with default value

@Value("${user.isActive:true}") private Boolean isActive;

The case where the property file contains variable but had no value.We can use expression with : to specify,If value not loaded from property file ,assign given value as default value.

@Value("${user.creator:Admin}") private String creator;

a. No space as prefix and suffix.
${user.creator:Admin}

b. Space as prefix. Space will be counted in default value.
${user.creator: Admin}

c. Space as prefix and suffix. Spaces will be counted in default value.
${user.creator: Admin }

10). @Value with Array

If we want to load array values from the propert file ,then we can load it by using @Value annotation.

in application.properties

user.status = pending,active,confirmed,archived,locked,disabled

and loading value in our class

@Value("${user.status}") private String[] userStatus;

To inject default array, we can use ${...} syntax as following.

@Value("${user.status :pending,active,confirmed,archived,locked,disabled}") private String[] userStatus;

When user.status property is not defined in property file, the default array will be injected to userStatus.

We can assign default values for array of int types also.

@Value("${user.status.ids:1,2,3,4,5}") private int[] userStatusIds;

11). @Value with List

Sometimes we nned to load values as list from the property file.

By using @Value annoation,We can inject the comma separated value to List type field using @Value with #{...} SpEL syntax and ${...} syntax as following.

@Value("#{'${user.status}'.split(',')}") private List<string> userStatusList;

Find the code snippet to inject default list value.

@Value("#{'${user.status:@Value("${user.status :pending,active,confirmed,archived,locked,disabled}")}'.split(',')}") private List userStatusList;

When user.status property is not defined in property file, the default list will be injected to userStatusList.

12). @Value with Map

We can load property value as key value pair ,using @Value annotation.

In our application.properties we have values like

user.status={1: 'active', 2: 'pending', 3: 'confirmed', 4: 'locked', 5: 'archived'}

And we want to load value as map then we can use like

@Value("#{${user.status}}") private Map<integer string> status;

To inject default map, we can use #{...} SpEL syntax with ${...} syntax as following.

@Value("#{${user.status: {1: 'active', 2: 'pending', 3: 'confirmed', 4: 'locked', 5: 'archived'}}}") private Map<integer string> status;

When user.status property is not defined in property file, the default map will be injected to status.

In this article, we have seen Spring @Value Annotation with examples.