Reputation: 3347
Stuck with the strange prob. I'm adding a ServletContext to my class (defined as @Service) and it always returns null. Tried both @Autowired and without it.
Also i didn't receive any error on app startup. Only the null value when i call 'servletContext.getRealPath("/WEB-INF/")'
This is a class where i'm trying to use it:
@Service
public class MyFactory implements ServletContextAware {
@Autowired
ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
private someMethod(){
servletContext.getRealPath("/WEB-INF/"); //this return null
}
}
P.S servletContext
itself is null, not a .getRealPath("/WEB-INF/")
method
Upvotes: 2
Views: 2529
Reputation: 159086
Your problem description is confusing. You say you add ServletContext
and it returns null (@Autowired
or not), making it sound like the value of servletContext
is null, when your wording and code example otherwise seems to indicate that getRealPath()
is returning null.
If servletContext
is null, then servletContext.getRealPath()
will cause a NullPointerException
.
If servletContext
is not null, then servletContext.getRealPath()
will succeed, but may return null.
Quoting javadoc of getRealPath()
:
This method returns
null
if the servlet container is unable to translate the given virtual path to a real path.
So, if /WEB-INF/
is in a .war file that hasn't been unpacked, there is no real path, and getRealPath()
will return null.
Upvotes: 1