【问题标题】:Why method contextInitialized doesn't invoke?为什么方法 contextInitialized 不调用?
【发布时间】:2013-10-21 15:08:47
【问题描述】:

我写了以下java类:

@Configuration
public class UiConfig {


    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
    @Bean
    public AppListener getAppListener(){
        AppListener appListener = new AppListener();
        System.out.println();
        System.out.println();
        System.out.println(" appListener method ");
        System.out.println();
        System.out.println();
        return appListener;
    }
    @Bean
    public MyListener getMyListener(){
        MyListener myListener = new MyListener();
        System.out.println();
        System.out.println();
        System.out.println(" myListener method ");
        System.out.println();
        System.out.println();
        return myListener;
    }
}
class MyListener extends ContextLoaderListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println();
        System.out.println();
        System.out.println(" hello ContextLoaderListener ");
        System.out.println();
        System.out.println();
    }
}
class AppListener implements ApplicationListener<ContextRefreshedEvent> {

        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            System.out.println();
            System.out.println();
            System.out.println(" hello AppListener");
            System.out.println();
            System.out.println();
        }

    }

我运行我的 tomcat 并查看下一个日志:

21.10.2013 18:56:18 org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in

...

org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,messageSource,getAppListener,getMyListener]; root of factory hierarchy


 appListener method 




 myListener method 




 hello AppListener


INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 4424 ms
21.10.2013 18:56:34 org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'

...

INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/updateVacancy],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.epam.hhsystem.web.controllers.VacancyMenuController.updateVacancyPRG(org.springframework.ui.Model,org.springframework.web.servlet.mvc.support.RedirectAttributes,java.lang.Integer)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/addVacancy],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.ModelAndView com.epam.hhsystem.web.controllers.VacancyMenuController.addVacancy(com.epam.hhsystem.model.vacancy.Vacancy,org.springframework.validation.BindingResult,org.springframework.ui.Model,org.springframework.web.servlet.mvc.support.RedirectAttributes)
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'


 appListener method 




 myListener method 




 hello AppListener




 hello AppListener


INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 926 ms
21.10.2013 18:56:34 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
21.10.2013 18:56:34 org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
21.10.2013 18:56:34 org.apache.catalina.startup.Catalina start
INFO: Server startup in 15692 ms
INFO : com.epam.hhsystem.web.controllers.CustomAuthentificationProvider - User with name 'Nikolay_tkachev' log in
/index
21.10.2013 19:01:01 org.apache.jasper.compiler.TldLocationsCache tldScanJar
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
21.10.2013 19:01:41 org.apache.catalina.core.StandardServer await
INFO: A valid shutdown command was received via the shutdown port. Stopping the Server instance.
21.10.2013 19:01:41 org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8080"]
21.10.2013 19:01:41 org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
21.10.2013 19:01:41 org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
21.10.2013 19:01:41 org.apache.catalina.core.ApplicationContext log
INFO: Destroying Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing WebApplicationContext for namespace 'appServlet-servlet': startup date [Mon Oct 21 18:56:34 MSK 2013]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5dd22889: defining beans [mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,baseMenuController,candidateMenuController,provider,eventMenuController,homeController,uiConfig,vacancyMenuController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,messageSource,getAppListener,getMyListener]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@19a072a6
21.10.2013 19:01:41 org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Mon Oct 21 18:56:29 MSK 2013]; root of context hierarchy

....

21.10.2013 19:01:41 org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-bio-8080"]
21.10.2013 19:01:41 org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["ajp-bio-8009"]
21.10.2013 19:01:41 org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-bio-8080"]
21.10.2013 19:01:41 org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-bio-8009"]

我不明白为什么我在此日志中看不到字符串 " hello ContextLoaderListener "? 能解释一下吗?

附言

在 web.xml 我有这个条目

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

【问题讨论】:

    标签: java spring servlets spring-mvc listener


    【解决方案1】:

    为什么方法 contextInitialized 不调用?

    你的班级

    class MyListener extends ContextLoaderListener {
    
        @Override
        public void contextInitialized(ServletContextEvent event) {
            System.out.println();
            System.out.println();
            System.out.println(" hello ContextLoaderListener ");
            System.out.println();
            System.out.println();
        }
    }
    

    是一个ServletContextListener,尚未注册到负责调用contextInitializedServlet 容器。因此,永远不会调用该方法。

    ServletContextListener 通常会在容器的web.xml 中注册一个&lt;listener&gt; 条目。

    【讨论】:

    • 如何将此侦听器绑定到调度程序 servlet?
    • @gstackoverflow 您不将其绑定到 DispatcherServlet,而是将其注册到 Servlet 容器。考虑查看 Spring 的 WebApplicationInitializer 接口。
    • 我在 web.xml 中有 条目
    • @gstackoverflow 当然,容器将注册一个ContextLoaderListener 的实例,但这不会是您在@Configuration 类中创建的实例。如果要动态注册侦听器,例如,从 Spring 应用程序上下文中,则需要使用 ServletContainerInitializer 或 Spring 的 WebApplicationInitializer
    • 使用ServletContainerInitializer需要什么条件?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2018-03-26
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多