Spring @Value default value

In this tutorial, we will show you how to set a default value for @Value

1. @Value Examples

To set a default value in Spring expression, use Elvis operator :


	#{expression?:default value}

Few examples :


	@Value("#{systemProperties['mongodb.port'] ?: 27017}")
	private String mongodbPort;

	@Value("#{config['mongodb.url'] ?: '127.0.0.1'}")
	private String mongodbUrl;	
	
	@Value("#{aBean.age ?: 21}")
	private int age;

P.S @Value has been available since Spring 3.0

2. @Value and Property Examples

To set a default value for property placeholder :


	${property:default value}

Few examples :


	//@PropertySource("classpath:/config.properties}")
	//@Configuration
	
	@Value("${mongodb.url:127.0.0.1}")
	private String mongodbUrl;
	
	@Value("#{'${mongodb.url:172.0.0.1}'}")
	private String mongodbUrl;
	
	@Value("#{config['mongodb.url']?:'127.0.0.1'}")
	private String mongodbUrl;
config.properties

mongodb.url=1.2.3.4
mongodb.db=hello

For “config” bean.


	<util:properties id="config" location="classpath:config.properties"/>

Follow up
Must register a static PropertySourcesPlaceholderConfigurer bean in either XML or annotation, so that Spring @Value know how to interpret ${}


  //@PropertySource("classpath:/config.properties}")
  //@Configuration

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
	return new PropertySourcesPlaceholderConfigurer();
  }

References

  1. Spring EL Expression
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000
newest oldest most voted
Shreyas Nargund
Guest
Shreyas Nargund

can you assign the default value with another property?
I tries something like this and it threw an error.

@Value(“${properties.myProperty:${properties.defaultProperty}}”)
private String myProperty;

Vigneshwaran Ganesan
Guest
Vigneshwaran Ganesan

Hi mkyong,

I have tried to implement the Annotation for reading the
property file but getting null for environment.

@Configuration
@PropertySource(“classpath: application.properties”)
Class Level

Inside the class
@Autowired
private Environment env;

Inside the Method
env.getProperty(key)

Conclusion: I am getting null value for env.getProperty(key).

Ciccio
Guest
Ciccio

thank you minkiong

Vincent
Guest
Vincent

Does ${property:default value} work as expected in Spring 3.2? I get “${property:default value}” but not “default value” when “property” not exist.

Daniel Garay
Guest
Daniel Garay

Hi!
Whats youre plugin js or css for the language formatter?
Its very pretty