2016-08-05 2 views
2

Я не могу получить WebApplicationContext внутри ServletContextListener. Я искал решение, но не они работают для меня. Буду признателен, если кто-то может помочь. Заранее спасибо.WebApplicationContextUtils.getWebApplicationContext (ServletContext) возвращает NULL из ServletContextListener

Ниже КОДИРУЙТЕ snippets- Мой AppConfig класс:

package in.andonsystem.config; 

import org.springframework.context.MessageSource; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.support.ResourceBundleMessageSource; 
import org.springframework.web.servlet.ViewResolver; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 
import org.springframework.web.servlet.view.InternalResourceViewResolver; 
import org.springframework.web.servlet.view.JstlView; 

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = {"in.andonsystem"}) 
public class AppConfig extends WebMvcConfigurerAdapter{ 

    @Bean 
    public ViewResolver viewResolver(){ 
     InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 
     viewResolver.setViewClass(JstlView.class); 
     viewResolver.setPrefix("WEB-INF/views/"); 
     viewResolver.setSuffix(".jsp"); 
     return viewResolver; 
    } 

    @Bean 
    public MessageSource messageSource(){ 
     ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); 
     messageSource.setBasename("messages");  
     return messageSource; 
    } 

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/static/**").addResourceLocations("/static/"); 
    } 
} 

My AppInitializer Class.

package in.andonsystem.config; 

import javax.servlet.ServletRegistration; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import org.springframework.web.WebApplicationInitializer; 
import org.springframework.web.context.ContextLoaderListener; 
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; 
import org.springframework.web.servlet.DispatcherServlet; 

public class Appinitializer implements WebApplicationInitializer{ 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); 
     rootContext.register(AppConfig.class); 
     rootContext.setServletContext(servletContext); 

     // Manage the lifecycle of the root application context 
     servletContext.addListener(new ContextLoaderListener(rootContext)); 
     rootContext.refresh(); 

     // Register and map the dispatcher servlet 
     ServletRegistration.Dynamic dispatcher = 
       servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext)); 
     dispatcher.setLoadOnStartup(1); 
     dispatcher.addMapping("/"); 

    } 
} 

Мои ContextListener Класс:

package in.andonsystem.config; 

import com.mysql.jdbc.AbandonedConnectionCleanupThread; 
import java.sql.Driver; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
import java.util.Enumeration; 
import java.util.logging.Logger; 
import javax.servlet.ServletContextEvent; 
import javax.servlet.ServletContextListener; 
import javax.servlet.annotation.WebListener; 
import org.springframework.web.context.WebApplicationContext; 
import org.springframework.web.context.support.WebApplicationContextUtils; 

@WebListener 
public class ContextListener implements ServletContextListener{ 

    private Logger logger = Logger.getLogger("ContextListener"); 


    @Override 
    public void contextInitialized(ServletContextEvent sce) { 
     logger.info("contextInitialized()"); 

     WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); 
     System.out.println("Is rootContext null:" + (rootContext == null)); 

    } 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) { 

    } 

} 

выход стандартный вывод всегда сбывается. Что мне не хватает?

ответ

1

И наконец, пришло решение. Проблема заключалась в том, что ServletContextListener загружался до ContextLoaderListener и поэтому возвращаемый WebApplicationContext был нулевым, поскольку ContextLoaderListener должен быть загружен до ServletContextListener, чтобы получить rootContext.

Я удалил аннотацию @WebListener из моего ContextListener и добавил этот прослушиватель программно в onStartup метод AppInitializer после добавления ContextLoaderListener.

Теперь мой ContextListener без @WebListener аннотации:

public class ContextListener implements ServletContextListener{ 

    private Logger logger = Logger.getLogger("ContextListener"); 


    @Override 
    public void contextInitialized(ServletContextEvent sce) { 
     logger.info("contextInitialized()"); 

     WebApplicationContext rootContext = 
       WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); 
     System.out.println("Is rootContext null:" + (rootContext == null)); 

    } 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) { 
     logger.info("contextDestroyed()"); 
    } 

} 

и AppInitializer является:

public class Appinitializer implements WebApplicationInitializer{ 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); 
     rootContext.register(AppConfig.class); 
     rootContext.setServletContext(servletContext); 

     // Manage the lifecycle of the root application context 
     servletContext.addListener(new ContextLoaderListener(rootContext)); 
     //ContextListener must be added after ContextLoaderListener 
     servletContext.addListener(ContextListener.class); 


     // Register and map the dispatcher servlet 
     ServletRegistration.Dynamic dispatcher = 
       servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext)); 
     dispatcher.setLoadOnStartup(1); 
     dispatcher.addMapping("/"); 

    } 
} 
0

выглядит в основном правильно, но я думаю, вы должны удалить следующие 2 строки из вашего класса инициализатора:

rootContext.setServletContext(servletContext); 

и

rootContext.refresh(); 
Смежные вопросы