Vivek
Vivek

Reputation: 2101

Load file from WEB-INF folder using Spring

I am trying to load a config file present under the WEB-INF folder of the application using Spring.

I tried using the

private @Autowired ServletContext servletContext;

and then

servletContext.getResourceAsStream("/WEB-INF/" + fileNm);

But the servletContext is being returned as null.

What am i doing wrong ?

My Methods look like this

public static SqlSessionFactory getSqlSessionFactory() {
  SqlSessionFactory  sqlSessionFactory = new SqlSessionFactoryBuilder().build(myConnObj.getIpStream("mybatis-config.xml"));
}

private InputStream getIpStream(String fileNm){
    InputStream inputStream = null;
    try{
        inputStream = servletContext.getResourceAsStream("/WEB-INF/" + fileNm);
    } catch(Exception ex) {
        ex.printStackTrace();
    }
    return inputStream;
}

Upvotes: 4

Views: 4595

Answers (1)

dimitrisli
dimitrisli

Reputation: 21421

What if you try to implement ServletContextAware in your class that would make it override:

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

which will give you the servletContext?

Upvotes: 4

Related Questions