Issue
I want to get the ServletContext in a Java Spring Webproject and use it to get the absolute path of my web-application project. I'm still a beginner in JavaEE and Spring, so maybe I've got some concepts wrong. In the java class, in which I want to use the ServletContext, I got only an empty object when using @Autowired ServletContext context; But in my RestConfiguartion class, which extends the WebMvcConfigurerAdapter class, I got the ServletContext and I'm able to use it in a Java Bean, with the return type of ServletContext. But I have no idea, how I can use the Bean in another class to get the ServletContext, is this possible?
@Configuration
@EnableWebMvc
@Import({ ServiceConfiguration.class, SecurityConfiguration.class })
@ComponentScan(basePackages = { "de.rest", "de.security" })
public class RestConfiguration extends WebMvcConfigurerAdapter {
@Autowired
ServletContext context;
@Bean
public ServletContext getServletContext() {
System.out.println("*** Context path: *** " + context.getRealPath("/"));
return context;
}}
Solution
You can write
@Autowired
ServletContext context;
In other bean annotated classes too. You'll get the same context. Because of it, you don't need to specify:
@Bean
public ServletContext getServletContext() {
System.out.println("*** Context path: *** " + context.getRealPath("/"));
return context;
}}
For example (any class in directories, specified in your annotation @ComponentScan
):
@Bean
class X {
@Autowired
ServletContext context;
...
}
Answered By - Nikita Ryanov