javascript
Spring注解@Value获取属性文件值且解决在controller无法获取到值的问题
一、說到@Value注解,用過的應該都知道,這是Spring3的一個注解,通過@value注解的方式獲取properties文件中的配置值,大大簡化了我們讀取配置文件的代碼
首先必須要配置properties文件的加載bean:在spring的配置文件中加入:讓spring將properties的文件中的內容加載進spring容器中,將properties加入到Spring容器中有兩種方式
1、以注入bean的形式
<bean id="appProperty"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><array><value>classpath:weixin.properties</value></array></property> </bean>2、以下面這種形式,加載多個properties文件使用,隔開;
<!-- 加載配置屬性文件 --><context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties,classpath:weixin.properties" />3、weixin.properties內容以鍵值對(key = value)形式存放
4、@Value使用
以 @Value("${key}")的形式獲取properties中key對應的value值 , 以下為獲取value值得代碼
5、問題 :但是上述步驟還存在一個問題,就是我在Service中通過 @Value("${token}") 可以獲取到token的值,但是在controller中無法獲取到token的值,若要在Controller層也使用@Value訪問properties配置的話,需要在xxx-servlet.xml(我這里是Spring-mvc.xml)中也定義properties配置文件。
解決 : 必須在Spring-mvc.xml中加入
<!-- 加載配置屬性文件 --><context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties,classpath:weixin.properties" />
總結 :
如上所示,同樣的代碼,寫在在業務層,運行時能取到正確的值,但在控制層卻取得了@Value注解中的Key(@Value注解有個特點,如果取不到值,那么不是返回一個null,而是返回Key)。
原因是controller注冊在dispatcherservlet-servlet.xml代表的Spring MVC的容器中,而service則注冊在application-context.xml代表的Spring的容器中。
如果context:property-placeholder只注冊在Spring的容器中,那么自然只有業務層的類可以取到enable-upload-image的值,而控制器取不到值。
解決方法就是把各種context:property-placeholder在兩個容器中都注冊一下。如:
并且現在可以從屬性文件讀取,這只是@Value其中一小部分用法,詳細請查閱資料,這次記錄只是記錄我在項目中所遇到的問題,方便記憶,以防止自己以后再入坑,有紕漏請指出,不喜勿噴!
作者:自由不過一種漂泊
原文:https://blog.csdn.net/Thinkingcao/article/details/80620240
總結
以上是生活随笔為你收集整理的Spring注解@Value获取属性文件值且解决在controller无法获取到值的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 带你学python基础:文件读写,俗称I
- 下一篇: 关于这件事,我有话要说!