spring @value

Posted 空白-键

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring @value相关的知识,希望对你有一定的参考价值。

转自:http://www.mkyong.com/spring3/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 @Valueknow how to interpret $

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

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


以上是关于spring @value的主要内容,如果未能解决你的问题,请参考以下文章

Spring @Value 为空 [重复]

Spring源码窥探之:Spring IOC之@Value

Spring @Value 用法小结

Spring中@Value的三种使用方式

spring 3 的 @value的使用

spring中的@Value注解