服务器starup的监听器和完全加载的所有spring bean

Pri*_*ngh 3 java spring servlets listener

在我的Web应用程序中,我想创建一个Listener,它会在我的服务器启动并且所有bean都被加载时得到通知.在那个Listener中,我想调用一个服务方法.我用过ServletContextListener.它有contextInitialized方法但它在我的情况下不起作用.它在服务器启动时但在spring bean创建之前就被驱散了.所以我得到服务类的实例为null.是否有其他方法来创建Listener.

Gab*_*uiu 7

我将在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

XML

    <bean class="com.package.ContextInitFinishListener">
        <constructor-arg>
            <bean class="com.package.MyService"/>
        </constructor-arg>
    </bean>
Run Code Online (Sandbox Code Playgroud)

这是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
    }
}
Run Code Online (Sandbox Code Playgroud)