@Value
功能:將一個SpEL(SpEL:spring表達式類似於ognl)表達式結果映射到功能處理方法的參數上
例子:獲取系統參數'java.vm.version'的值給到變量jvmVersion
@RequestMapping(value = "/login") public String test1(@Value("#{systemProperties['java.vm.version']}") String jvmVersion){ return "hello"; }
所以@Value可以理解為:將某個參數的值賦給某個變量供程序使用,比如說ip地址,或者自己配置的某些參數值等等
那么問題來了,@Value獲取某個參數的值並不是隨隨便便就能取到的,需要遵循一定的格式。
下面講解@Value取值的兩種配置方式:
1. @Value("#{configProperties['qinqin.name']}")
2. @Value("${qinqin.name}")
1. 使用方式1需要在spring配置文件中添加:
<!-- @Value --> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath*:qinqin.properties</value> </list> </property> </bean>
並在src下添加配置文件qinqin.properties,內容如下:
qinqin.name=qinqin
qinqin.age=27
2.使用方式2需要在spring配置文件中添加:從配置也可以看出來,方式2包含了方式1,方式2在使用上更簡潔
<!-- @Value --> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath*:qinqin.properties</value> </list> </property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties" /> </bean>
注意:
@Value("${qinqin.name}")里面的qinqin指的是配置文件里面的qinqin.name=qinqin並不是文件名qinqin.properties;
如果配置項寫的是name=qinqin則使用@Value("${name}")獲取。