【问题标题】:Listener for server starup and all spring bean loaded completely服务器启动监听器和所有spring bean完全加载
【发布时间】:2014-05-28 01:55:13
【问题描述】:

在我的 Web 应用程序中,我想创建侦听器,当我的服务器启动并加载所有 bean 时它会收到通知。 在那个监听器中,我想调用一个服务方法。 我用ServletContextListener。 它有contextInitialized 方法,但在我的情况下不起作用。它在服务器启动时但在 spring bean 创建之前被调用。 所以我得到服务类的实例为空。 有没有其他方法来创建监听器。

【问题讨论】:

    标签: java spring servlets listener


    【解决方案1】:

    我会去在 Spring 上下文配置中注册一个 ApplicationListener 的实例,它会监听 ContextRefreshedEvent,当应用程序上下文完成初始化或刷新时发出信号。在此之后,您可以调用您的服务。

    您将在下面找到实现此目的所需的 ApplicationListener 实现(取决于服务)和 Spring 配置(Java 和 XML)。您需要选择特定于您的应用的配置:

    基于 Java 的配置

    @Configuration
    public class JavaConfig {
    
        @Bean
        public ApplicationListener<ContextRefreshedEvent> contextInitFinishListener() {
            return new ContextInitFinishListener(myService());
        }
    
        @Bean
        public MyService myService() {
            return new MyService();
        }
    }
    

    XML

        <bean class="com.package.ContextInitFinishListener">
            <constructor-arg>
                <bean class="com.package.MyService"/>
            </constructor-arg>
        </bean>
    

    这是 ContextInitFinishListener 类的代码:

    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextRefreshedEvent;
    
    public class ContextInitFinishListener implements ApplicationListener<ContextRefreshedEvent> {
    
        private MyService myService;
    
        public ContextInitFinishListener(MyService myService) {
            this.myService = myService;
        }
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            //call myService
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用Spring's event handling。您要查找的事件可能是ContextRefreshedEvent

      【讨论】:

        【解决方案3】:

        是的,您需要在 web.xml 中添加 ContextLoaderListener,仅当您想在加载应用程序时同时加载其他 Spring 上下文 xml 文件并且您可以指定它们时作为

        <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-security.xml
        </param-value>
        </context-param>
        

        更多你可以访问这个链接可能对你有帮助。

        Click Here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-03-19
          • 1970-01-01
          • 1970-01-01
          • 2015-07-24
          • 1970-01-01
          • 2015-12-20
          • 1970-01-01
          相关资源
          最近更新 更多