简体   繁体   中英

Define Spring bean which depends on file

How could I define a Spring bean which depends on a configuration file that resides in /WEB-INF folder? One of my beans has a constructor which takes a filename of configuration file as an argument.

The problem is when I'm trying to instantiate a Spring IoC container - it fails. I've got a FileNotFound exception, when Spring IoC container tries to create the following bean:

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

Here's a part of web.xml file where I defined 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>

Is there any solution for this case?

// StackOverflow doesn't let me answer my question, so I post a solution here:

The solution is - your bean class has to implement the following interface - http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/ServletContextAware.html . The Spring IoC container notifies all classes which implement this interface that ServletContext has been instantiated. Then, you have to use ServletContext.getRealPath method to get the path to the file which resides somewhere in the WEB-INF folder. In my case the bean configuration file beans.xml stays the same. The final version of Bean class is shown below:

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

I hope this might help someone, but if you know better solution - share it please.

Try moving config.json to your resources folder and make sure this file is in you classpath. Next, use value="/config/config.json" (or value="config/config.json" I do not remember for sure if has or has not a leading slash :] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM