簡體   English   中英

定義依賴文件的Spring bean

[英]Define Spring bean which depends on file

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

問題是當我嘗試實例化Spring IoC容器時-它失敗。 當Spring IoC容器嘗試創建以下bean時,我有一個FileNotFound異常:

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

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

<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;
    }
}

希望對您有所幫助,但是,如果您知道更好的解決方案,請與我們分享。

嘗試將config.json移到資源文件夾,並確保此文件在類路徑中。 接下來,使用value="/config/config.json" (or value="config/config.json"我不記得是否有斜杠:])。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM