Spring 註解@value引數值的兩種形式
阿新 • • 發佈:2019-01-03
首先,@value需要引數,這裡引數可以是兩種形式:@Value("#{configProperties['t1.msgname']}")或者@Value("${t1.msgname}");
其次,下面我們來看看如何使用這兩形式,在配置上有什麼區別:
1、@Value("#{configProperties['t1.msgname']}")這種形式的配置中有“configProperties”,其實它指定的是配置檔案的載入物件:配置如下:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/config/t1.properties</value>
</list>
</property>
</bean>
這樣配置就可完成對屬性的具體注入了;
2、@Value("${t1.msgname}")這種形式不需要指定具體載入物件,這時候需要一個關鍵的物件來完成PreferencesPlaceholderConfigurer,這個物件的配置可以利用上面配置1中的配置,也可以自己直接自定配置檔案路徑。
如果使用配置1中的配置,可以寫成如下情況:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
如果直接指定配置檔案的話,可以寫成如下情況:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location">
<value>config/t1.properties</value>
</property>
</bean>
其次,下面我們來看看如何使用這兩形式,在配置上有什麼區別:
1、@Value("#{configProperties['t1.msgname']}")這種形式的配置中有“configProperties”,其實它指定的是配置檔案的載入物件:配置如下:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/config/t1.properties</value>
</list>
</property>
</bean>
這樣配置就可完成對屬性的具體注入了;
2、@Value("${t1.msgname}")這種形式不需要指定具體載入物件,這時候需要一個關鍵的物件來完成PreferencesPlaceholderConfigurer,這個物件的配置可以利用上面配置1中的配置,也可以自己直接自定配置檔案路徑。
如果使用配置1中的配置,可以寫成如下情況:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties"/>
</bean>
如果直接指定配置檔案的話,可以寫成如下情況:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location">
<value>config/t1.properties</value>
</property>
</bean>