1. 程式人生 > >spring中讀不到配置檔案問題

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有關,本人還比較菜沒有深入去了解。