Spring 事件机制(ApplicationListener)

1. 事件类型

A. ContextRefreshedEvent —— ApplicationContext容器初始化或者刷新时触发该事件;

    B. ContextStartedEvent —— 当使用ConfigurableApplicationContext接口的start()方法启动ApplicationContext容器时触发该事件;

    C. ContextClosedEvent —— 当使用ConfigurableApplicationContext接口的close()方法关闭ApplicationContext容器时触发该事件;

    D. ContextStopedEvent —— 当使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器时触发该事件。

2. 举例

package com.ruhuanxingyun;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.nsac.business.listener.ApplicationStartup;

@SpringBootApplication
public class SpApp {
    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(SpApp.class);
        springApplication.addListeners(new ApplicationStartup());
        springApplication.run(args);
    }
}
package com.nsac.ruhuanxingyun;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext ac = event.getApplicationContext();
        StepExecutor StepExecutor = new StepExecutor(ac.getEnvironment().getProperty("project-id"), ac.getBean("businessSingleJedisPool",redis.clients.jedis.JedisPool.class), 
                                ac.getBean("redisCluster", redis.clients.jedis.JedisCluster.class));
        Thread thread = new Thread(StepExecutor);
        thread.start();
    }

}

 

Spring 事件机制(ApplicationListener)

上一篇:微信6.0.2内置浏览器网页分享控制失效应急办法


下一篇:pygame开发PC端微信打飞机游戏