2016-09-30 4 views
1

Spring 프로젝트에서 리스너 유형을 ServletContextListener으로 사용했습니다. @Autowired 인 인스턴스 필드를 사용했지만 contextInitialized(event) 메서드에서 autowired 인스턴스 변수를 사용할 수 없다면 NullpointerException을 던집니다. ServletContextListener에서 @Autowired 인스턴스 변수를 사용하는 방법

는 어떻게이 상황에 맞는 초기화 한 후 초기화 할거야이

+1

당신이 수동으로 배선해야합니다; Spring은 Java EE 서버가 수행하는 리스너를 생성하지 않습니다. 어떻게'ApplicationContext'를 만들 수 있습니까? [this] (http://stackoverflow.com/a/21914004/2071828)를보십시오. –

답변

0

음, 봄 보장을 위해 @Autowired를 사용할 수 있습니다.

가 초기화 있어요 후에는 사용하여 액세스 할 수 있습니다

MyClass myClass = ctx.getBean(MyClass.class); 

을 다른 말로하면 : 당신이 당신의 애플리케이션 컨텍스트 마지막으로 초기화 Bean 전에를 초기화하는 봄을 강제로 계약을 만들기위한 @Autowired을 사용할 수 없습니다.

1

수 없습니다. @Autowired은 컨텍스트가 초기화 된 후에 만 ​​작동합니다.

public class MyListener implements ServletContextListener { 

    private MyBean myBean;  

    @Override 
    public void contextInitialized(ServletContextEvent event) { 
     WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); 
     this.myBean = (MyBean)ctx.getBean("myBean"); 
    } 

} 

또는 더 나은 솔루션 보리스 거미에 들으 다음과 같습니다 :

그래서이 해킹을 할 수

public class MyListener implements ServletContextListener { 

    @Autowired 
    private MyBean myBean;  

    @Override 
    public void contextInitialized(ServletContextEvent event) { 
     WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); 
     ctx.autowireBean(this); 
    } 

} 
+1

컨텍스트가 있으면'autowireBean (this)'...을 호출하면됩니다. –

관련 문제