2013-07-15 120 views
0

如何定義一個依賴駐留在/ WEB-INF文件夾中的配置文件的Spring bean? 我的一個bean有一個構造函數,它將配置文件的文件名作爲參數。定義依賴於文件的Spring bean

問題是,當我試圖實例化一個Spring IoC容器 - 它失敗了。 我有一個FileNotFound例外,當Spring IoC容器嘗試創建下面bean:

<bean id="someBean" class="Bean"> 
    <constructor-arg type="java.lang.String" value="WEB-INF/config/config.json"/> 
</bean> 

這裏的web.xml文件的一部分,我定義的ContextLoaderListener:

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/beans.xml</param-value> 
</context-param> 

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

有什麼這個案例的解決方案?

// StackOverflow上並不讓我回答我的問題,所以我在這裏發佈的解決方案:

解決的辦法是 - 你的bean類必須實現以下接口 - http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/ServletContextAware.html。 Spring IoC容器通知實現此接口的所有類,該接口實例化了ServletContext。然後,您必須使用ServletContext.getRealPath方法來獲取駐留在WEB-INF文件夾某處的文件的路徑。在我的情況下,bean配置文件beans.xml保持不變。 Bean類的最終版本如下:

public class Bean implements ServletContextAware { 

    private Map<String, String> config; 
    private ServletContext ctx; 
    private String filename; 


    public Bean(String filename) { 
     this.filename = filename; 
    } 

    public Map<String, String> getConfig() throws IOException { 
     if (config == null) { 
      String realFileName = ctx.getRealPath(filename); 

      try (Reader jsonReader = new BufferedReader(new FileReader(realFileName))) { 
       Type collectionType = new TypeToken<Map<String, String>>(){}.getType(); 

       config = new Gson().fromJson(jsonReader, collectionType); 
      } 
     } 

     return config; 
    } 

    @Override 
    public void setServletContext(ServletContext servletContext) { 
     this.ctx = servletContext; 
    } 
} 

我希望這可以幫助別人,但如果你知道更好的解決方案 - 分享吧。

回答

0

嘗試將config.json移動到您的資源文件夾中,並確保此文件在您的類路徑中。接下來,使用value="/config/config.json" (or value="config/config.json"我不確定是否有或沒有前導斜槓:])。

+0

不幸的是,它沒有幫助,但我剛剛找到了解決方案。檢查我編輯的消息。 – maseev

相關問題