1. 程式人生 > >spring的value標籤獲取不值原樣輸出${}

spring的value標籤獲取不值原樣輸出${}

前提已經確保spring的配置檔案以及讀取到properties檔案了我的配置是:
<!-- 引入屬性檔案 -->
<context:property-placeholder location="classpath:filer.properties" order="4" ignore-unresolvable="true"/>


spring的value標籤注入properties配置檔案的值在Controller中輸入${"name"},但是在service層就可以
獲取到配置檔案的值。


經過上面的分析,足以說明是Controller層和service層的問題引起的,因為service層可以讀取到值,
那麼是什麼原因導致Controller原樣輸出了${}這些東西呢?


@Value取不到值引出的spring的2種配置檔案applicationContext.xml和xxx-servlet.xml


我的另一篇部落格有一種解決辦法,但是感覺不夠好(需要的可以進入部落格去找下),那種辦法就是在每個xxx-servlet.xml中都掃描配置檔案,
那我這裡介紹的就是在applicationContext.xml中掃描一次,但是暴露自己的Id,在其他的xxx-servlet.xml中引入這個物件就可以了,下面是配置
applicationContext.xml掃描方式:
<!-- 引入屬性檔案 -->
<bean id="global" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array>
<value>classpath:config/file.properties</value>
</array>
</property>
</bean>
這裡暴露的Id是global,
下面是xxx-servlet.xml的配置檔案:
<!-- 引入其他容器的配置 -->
<context:property-placeholder properties-ref="global" />
這樣就可以注入物件了,下面有個注意點:(不要el表示式寫多了這裡後面寫空格,除非你的配置檔名稱的後面真的有空格,不如會找不到)
正確寫法:@Value(value = "${file.serverPath}")
錯誤寫法:@Value(value = "${file.serverPath }")