服务器启动侦听器,并且所有spring bean均已完全加载 [英] Listener for server starup and all spring bean loaded completely

查看:260
本文介绍了服务器启动侦听器,并且所有spring bean均已完全加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Web应用程序中,我想创建侦听器,该侦听器将在我的服务器启动并加载所有bean时得到通知. 在该侦听器中,我想调用一个服务方法. 我使用了ServletContextListener. 它具有contextInitialized方法,但在我的情况下不起作用.它在服务器启动时但在创建Spring bean之前就卷入了. 所以我得到服务类的实例为空. 还有其他创建监听器的方法.

In my web application, I want to create Listener which will get notified when my server get started and all bean get loaded. In that Listener, I want to call a service method. I used ServletContextListener. it has contextInitialized method but it does not work in my case. it get involked when server get started but before spring bean creation. so I get instance of service class as null. Is there other way to create Listener.

推荐答案

我将在Spring上下文配置中注册 ApplicationListener 的实例,以侦听 ContextRefreshedEvent ,当应用程序上下文完成初始化或刷新时发出信号.此刻之后,您可以致电服务.

I would go for registering an instance of ApplicationListener in the Spring context configuration, that listens for the ContextRefreshedEvent, which is signalled when the application context has finished initializing or being refreshed. After this moment you could call your service.

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

Below you will find the ApplicationListener implementation (which depends on the service) and the Spring configuration (both Java and XML)that you need to achieve this. You need to choose the configuration specific to your app:

基于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类的代码:

This is the code for the ContextInitFinishListener class:

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

这篇关于服务器启动侦听器,并且所有spring bean均已完全加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆