title: Spring 3 receive servletContext in custom bean
body: <p>my problem is that I can't get servletcontext in my bean.
  I created custom bean "FileRepository" and I need to get ServletContext there.
  here is the code</p>
  
  <pre><code>package com.pc.webstore.utils;
  
  import java.io.File;
  import java.nio.file.Files;
  
  import javax.servlet.ServletContext;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.context.annotation.Configuration;
  import org.springframework.web.context.ServletContextAware;
  public class FileRepository implements ServletContextAware {
  
  private ServletContext servletContext;
  
  public String saveFile(File file){
      File tempdir = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
              ...
  }
  
  @Override
  public void setServletContext(ServletContext servletContext) {
      this.servletContext = servletContext;
      }
  }
  </code></pre>
  
  <p>registration in ApplicationContext.xml</p>
  
  <pre><code> &lt;bean id="fileStorage" class="com.pc.webstore.utils.FileRepository"/&gt;
  </code></pre>
  
  <p>when saveFile(File file) starts, I recive Nullpointerexception because servletContext == null.</p>
  
  <p><strong>So why servletcontext does not injected?</strong> 
  I have ContextLoaderListener registred in web.xml</p>
  
  <pre><code>   &lt;listener&gt;
          &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
      &lt;/listener&gt;
  </code></pre>
  
  <p>I found that there is some scopes. May be problem is there. Tell me briefly about applicationsontext scope or give the link pleas.
  Thanks for help. I spent a lot of time for this problem.</p>
  
  <p>After some debuging I understood that setServletContexr method of servletcontextaware is actually was called when app starts but when I tried to store file with FileRepository from my controller, it was already anather object with null servletContext field.</p>
  
  <p>Is there a way just to autowier servlet context in my custom bean when i want, like in controller?</p>
  
  <p>Finaly I get servletContext via ServletContextAware. I change the way of creation fileRepository bean. From this</p>
  
  <pre><code>public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, FileRepository fileRepository)     {
  </code></pre>
  
  <p>to this </p>
  
  <pre><code>@Autowired
  private FileRepository fileRepository;
  
  @RequestMapping(method = RequestMethod.POST, produces = "text/html")
  public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
  </code></pre>