Spring get ServletContext and provide it as a Bean

Viewed 10344

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

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;

    ...
}

Thanks to your help I've solved it, by adding the package of my target class to @ComponentScan, declared my target class @Component and inserted the Bean I used before. Theses are the resulting code snippets:

...
@ComponentScan(basePackages = { "de.rest", "de.security", "de.targetPackage" })
public class RestConfiguration extends WebMvcConfigurerAdapter {
...



@Component
public class targetClass {

  private static String absoluteServletContextPath;

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    absoluteServletContextPath = context.getRealPath("/");
    System.out.println(absoluteServletContextPath);
    return context;
  }

  @Override
  public void myMethod {

        absoluteServletContextPath = absoluteServletContextPath.replaceAll("webapp\\\\", "")
          .replaceAll("\\\\", "/");}}
Related