spring中讀不到配置文件問題

最近碰到一個問題,明明已經配置了<context:property-placeholder location="classpath:bieyang-config.properties" />

啓動spring還是報找不到${bieyang.host}類似這種錯誤,查了一天,各種試驗。得出如下結論:

1,首先<context:property-placeholder location="classpath:bieyang-config.properties" />這個配置項目中只能用一次。

2.<context:property-placeholder location="classpath:bieyang-config.properties" />這個配置的意思是把屬性加載到context中了,那麼問題來了,一般我們的項目中會有2個以上servletcontext,一個是通過listener創建

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:bean/spring-web.xml</param-value>
	</context-param>
<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
還有就是通過servlet方式創建

<servlet>
		<servlet-name>webapp</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>classpath:bean/webapp-servlet.xml</param-value>  
  </init-param>  
		<load-on-startup>3</load-on-startup>
	</servlet>
如果你把<context:property-placeholder location="classpath:bieyang-config.properties" />寫到其中一個context的xml中,而你又在兩個context中的xml中都要通過屬性文件讀取屬性值,這個是不行的。你只能把需要讀取屬性文件的配置寫到同一個context的xml中。

這裏順便提一下,

    <!-- 啓用緩存註解功能,這個是必須的,否則註解不會生效,另外,該註解一定要聲明在spring主配置文件中才會生效 -->   
<!--      需要注意的是<cache:annotation-driven/>只會去尋找定義在同一個ApplicationContext下的@Cacheable等緩存註解。  -->
<!--  proxy-target-class="true" 看情況要不要用-->
<!--     <cache:annotation-driven cache-manager="cacheManager"  />     -->
<cache:annotation-driven/>  
      
    

	<!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->
	<mvc:annotation-driven />
這種啓用註解功能的配置必須放到
DispatcherServlet對應的servletcontext的xml中才能生效,因爲註解比如@cacheable它的作用範圍也和servletcontext有關,本人還比較菜沒有深入去了解。



發佈了32 篇原創文章 · 獲贊 5 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章