定义依赖于文件的Spring bean

时间:2013-07-15 03:29:58

标签: java spring filenotfoundexception web-inf

如何定义依赖于驻留在/ WEB-INF文件夹中的配置文件的Spring bean? 我的一个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;
    }
}

我希望这对某些人有帮助,但如果你知道更好的解决方案 - 请分享。

1 个答案:

答案 0 :(得分:0)

尝试将config.json移动到资源文件夹,并确保此文件位于类路径中。接下来,使用value="/config/config.json" (or value="config/config.json"我不记得是否有或没有前导斜杠:])。