Home  >  Spring 5

Spring @Value Default Value

By Arvind Rai, April 17, 2019
Spring @Value annotation is used for expression-driven dependency injection. @Value can configure default value to be used when actual value is not available for dependency injection. @Value uses ${...} and #{...} syntax to write expression.
1. ${...} is a property placeholder syntax. We need to use colon (:) to specify default value with it.
@Value("${cp.user.name:Shree Mahesh}")
private String userName; 
2. #{...} is a SpEL syntax. It can also handle property placeholders and a lot more. We need to use Elvis Operator (?:) to specify default value with it.
@Value("#{systemProperties['unknown_prop_key'] ?: 'Default System Value'}") 
private String mySystemVal; 
We read property file using @PropertySource annotated at JavaConfig and resolve dependency injection using @Value annotation. Here we will discuss to specify default values with @Value for string, boolean, integer, list and map type fields.

Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.1.6.RELEASE
3. Spring Boot 2.1.4.RELEASE
4. Gradle 5.0
5. Eclipse 2018-09

1. String Default Value

To resolve dependency injection using @Value we use ${...} and #{...} syntax to write expression.
1. We need to use colon (:) to specify default value with ${...} syntax. Suppose we have a property file myproject.properties file. In our JavaConfig, we read property file with @PropertySource annotation.
@Configuration
@PropertySource("classpath:myproject.properties")
public class AppConfig {
  @Value("${cp.user.name:Shree Mahesh}")
  private String userName;
 ------
} 
When cp.user.role property is not defined in property file, the default value Shree Mahesh will be injected to userName field. To specify default value with ${...} syntax, we need not to enclose default value with single quotes ('').
If we prefix a space to default value after :, then that will be included in default value. If we suffix a space to default value before }, it will also be included in default value. Look into the following code snippet.
a. No space as prefix and suffix.
${cp.user.name:Shree Mahesh} 
b. Space as prefix. Space will be counted in default value.
${cp.user.name: Shree Mahesh} 
c. Space as prefix and suffix. Spaces will be counted in default value.
${cp.user.name: Shree Mahesh } 

2. If we want to pick default value from property file then we can use ${...} syntax as following.
@Value("${cp.user.role:${cp.user.role.default}}")
private String userRole; 
When cp.user.role property is not defined in property file, the default value will be injected to userRole picking it from cp.user.role.default property.

3. To specify default value with #{...} SpEL syntax, we need to use Elvis Operator (?:) as following.
@Value("#{systemProperties['unknown_prop_key'] ?: 'Default System Value'}") 
private String mySystemVal; 
In the above code snippet, for the demo, we are trying to fetch value from system properties for an unknown key. As the value will be null, so default value will be injected to mySystemVal.

2. Boolean Default Value

To specify Boolean default value, find the code snippet.
@Value("${cp.user.active:true}")
private Boolean isUserActive; 
When cp.user.active property is not defined in property file, then true will be injected to isUserActive.

3. Integer Default Value

To specify Integer default value, find the code snippet.
@Value("${cp.user.age: 30}")
private Integer userAge; 
When cp.user.age property is not defined in property file, then 30 will be injected to userAge.

4. Array Default Value

To inject default array, we can use ${...} syntax as following.
@Value("${cp.user.skills:Java,Spring,Angular}")	
private String[] userSkills; 
When cp.user.skills property is not defined in property file, the default array will be injected to userSkills.
In the same way, we can inject primitive datatype integer array as default value, too.
@Value("${cp.user.skillids:5,6,7}")		
private int[] userSkillIds; 

5. List Default Value

To inject default list value, we can use #{...} SpEL syntax with ${...} syntax as following.
@Value("#{'${cp.user.skills:Java,Spring,Angular}'.split(',')}") 
private List<String> userSkills; 
When cp.user.skills property is not defined in property file, the default list will be injected to userSkills.

6. Map Default Value

To inject default map, we can use #{...} SpEL syntax.
@Value("#{${cp.user.teamMates: {100: 'Krishna', 200: 'Shiva'}}}")
private Map<Integer, String> teamMates; 
When cp.user.teamMates property is not defined in property file, the default list will be injected to teamMates.

7. Default null

To assign a null value as default, we can specify #{null} as following.
@Value("${cp.user.country:#{null}}")
private String userCountry; 
When cp.user.country is not defined in property file, then userCountry will be injected with null value.

Complete Example

AppConfig.java
package com.concretepage;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:myproject.properties")
public class AppConfig {
	 //Default String
	 @Value("${cp.user.name:Shree Mahesh}")
	 private String userName;
	 
	 @Value("${cp.user.role:${cp.user.role.default}}")
	 private String userRole;
	 
	 @Value("${cp.user.country:India}")
	 private String userCountry;
	 
	 //Default Boolean
	 @Value("${cp.user.active:true}")
	 private Boolean isUserActive;
	 
	 //Default Integer
	 @Value("${cp.user.age: 30}")
	 private Integer userAge;	 

	 //Default using SpEL with Elvis Operator (?:)
	 @Value("#{systemProperties['unknown_prop_key'] ?: 'Default System Value'}") 
	 private String mySystemVal;	 
	 
	 //Default for List
	 @Value("#{'${cp.user.skills:Java,Spring,Angular}'.split(',')}") 
	 private List<String> userSkills;
	 
	 //Default for Map
	 @Value("#{${cp.user.teamMates: {100: 'Krishna', 200: 'Shiva'}}}")
	 private Map<Integer, String> teamMates;
	 
	 @Bean
	 public User getUser() {
		 User user = new User();
		 user.setUserName(userName);
		 user.setUserRole(userRole);
		 user.setUserCountry(userCountry);
		 user.setUserActive(isUserActive);
		 user.setUserAge(userAge);
		 user.setMySystemVal(mySystemVal);
		 user.setUserSkills(userSkills);
		 user.setTeamMates(teamMates);
		 return user;
	 }
} 
myproject.properties
cp.user.country= USA
cp.user.role.default= Contributor 
User.java
package com.concretepage;
import java.util.List;
import java.util.Map;
public class User {
	private String userName;
	private String userRole;
	private String userCountry;
	private Boolean userActive;
	private Integer userAge;
	private String mySystemVal;
	private List<String> userSkills;
	private Map<Integer, String> teamMates;
        //Setters and Getters
} 
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'spring-demo'

repositories {
    mavenCentral()
}
dependencies {
    compile  'org.springframework.boot:spring-boot-starter:2.1.4.RELEASE'
} 
MySpringApp.java
package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.scan("com.concretepage");
		ctx.refresh();
		User user = ctx.getBean(User.class);
		
		System.out.println("userName: " + user.getUserName());
		System.out.println("userRole: " + user.getUserRole());
		System.out.println("userCountry: " + user.getUserCountry());
		System.out.println("userActive: " + user.getUserActive());
		System.out.println("userAge: " + user.getUserAge());
		System.out.println("mySystemVal: " + user.getMySystemVal());
		System.out.println("userSkills: " + user.getUserSkills());
		System.out.println("teamMates: " + user.getTeamMates());
		
		ctx.registerShutdownHook();
		ctx.close();
	}
}
Output
userName: Shree Mahesh
userRole: Contributor
userCountry: USA
userActive: true
userAge: 30
mySystemVal: Default System Value
userSkills: [Java, Spring, Angular]
teamMates: {100=Krishna, 200=Shiva} 

References

Spring @Value
Spring Expression Language (SpEL)

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us