2012-05-19 2 views
3

내 문제는 내 콩에서 servletcontext를 얻을 수 없다는 것입니다. 커스텀 bean "FileRepository"를 생성했고 거기에 ServletContext를 가져와야합니다. SAVEFILE (파일 파일) 시작할 때 는 여기에 내가 NullPointerException이 받아 봐, ApplicationContext.xml스프링 3 사용자 정의 콩에서 servletContext를 수신

<bean id="fileStorage" class="com.pc.webstore.utils.FileRepository"/> 

의 코드

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

등록 왜냐하면의 servletContext == null를 돌려줍니다.

왜 servletcontext가 삽입되지 않습니다? 나는 web.xml을

좀 범위가 있음을 발견
<listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 

에서의 ContextLoaderListener는 registred 있습니다. 문제가있을 수 있습니다. applicationsontext 범위에 대해 간단히 설명하거나 링크를 알려주십시오. 도움 주셔서 감사합니다. 나는이 문제에 많은 시간을 보냈다.

일부 디버깅 후 servletcontextaware의 setServletContextr 메서드는 실제로 응용 프로그램이 시작될 때 호출되었지만 내 컨트롤러에서 FileRepository를 사용하여 파일을 저장하려고 시도했을 때 null servletContext 필드가있는 anather 개체였습니다.

컨트롤러와 같이 원할 때 내 사용자 정의 bean에서 서블릿 컨텍스트를 autowier하는 방법이 있습니까?

마지막으로 ServletContext를 ServletContextAware를 통해 얻습니다. 나는 fileRepository 빈의 생성 방법을 바꾼다. 이

public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, FileRepository fileRepository)  { 

에서이

@Autowired 
private FileRepository fileRepository; 

@RequestMapping(method = RequestMethod.POST, produces = "text/html") 
public String create(@Valid Item item, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) { 

답변

4

의 ContextLoaderListener에 응용 프로그램에 대한 글로벌 상위 문맥이되는 ApplicationContext를로드합니다. 거기에 ServletContext가 없습니다. ServletContext는 서블릿 (예 : DispatcherServlet)의 CONTEXT 내에 만 존재합니다 (용어의 과부하). 모든 DispatcherServlet은 ContextLoaderListener에 의해 등록 된 전역 부모 컨텍스트를 가리키는 하위 컨텍스트를 등록합니다. ApplicationContext는 클래스 로더와 같습니다. IOC 컨테이너가 bean을 "찾고"갈 때, 각 ApplicationContext는 부모에게 "올려다"보고 그것을 찾으려고하지만 아래로 내려다 볼 수는 없다. 자식은 부모 컨텍스트의 빈 정의를 재정의 할 수도 있습니다.

지금은 발견 할 ServletContext가없는 전역 상위 컨텍스트에서 bean이 정의된다는 것입니다. (자식에게 "내려다보고"찾을 수는 없습니다.)

fileStorage bean 정의를 DispatcherServlet의 ApplicationContext로 이동해야합니다.

web.xml에 DispatcherServlet을 정의 할 때 일반적으로 하위 컨텍스트를 정의하는 파일을 찾을 수있는 위치를 지정합니다. 마찬가지로 :

<servlet> 
    <servlet-name>dispatcherServlet</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>classpath:/web-context/*.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

bean 정의를 contextConfigLocation에 지정된 위치로 이동하면 모든 것이 예상대로 작동합니다.

+0

나는 WEB-INF/봄/webmvc-config.xml의 에 콩 등록의 위치를 ​​변경해야하지만, 난 단지 응용 프로그램 시작의 servletContext를 받아 봐. 그리고 fileRepository.saveFile()을 호출하면 fileRepository는 servletContext가 정의되지 않은 anather 인스턴스입니다. bean을 사용할 때 bean에 servletContext를 autowire하는 방법이 있습니까? 컨트롤러처럼. @autowired 개인 ServletContext servletContext; 감사합니다. . –

+0

컨트롤러의 메서드 매개 변수와 같은 fileRepository를 가져 오는 것이 문제 일 수 있습니다. –

+0

FileRepository가 두 가지 인스턴스가 있다고 주장합니까? 그렇다면 ApplicationContext 계층 구조에 관한 내 의견의 컨텍스트에서 수행중인 작업을 검토하십시오. 자식 컨텍스트에 정의되지 않은 다른 bean이 자식 컨텍스트에도 정의되지 않은 FileRepository로 주입되면 FileRepository가 원래의 문제를 계속 표시합니다. ServletContext에 의존하는 (또는 그것에 의존하는 것에 의존하는) 모든 것이 부모 컨텍스트가 아닌 자식 컨텍스트에 정의되어 있는지 확인해야합니다. 도움을 주신 분께 –

관련 문제