springboot启动和关闭时的事件操作:

/ Java / 没有评论 / 2053浏览

本章节不是太重要,但你要知道有这个东西存在。

销毁时执行:

继承自DisposableBean,并将其注册为bean即可.

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
/**
 * 结束的时候执行
 * @author dmw
    *
 * 2019年4月15日
    */
    @Component
    public class MyDisposableBean implements DisposableBean{
    
    @Override
    public void destroy() throws Exception {
    	System.out.println("结束");	
    }
}

启动后执行:

其有两种方法:

  1. 实现自ApplicationRunner
@Component
public class MyApplicationRunner1 implements ApplicationRunner{

	@Override
	public void run(ApplicationArguments args) throws Exception {
		
	}

}
  1. 实现自CommandLineRunner
@Component
public class MyCommandLineRunner1 implements CommandLineRunner{
	@Override
	public void run(String... args) throws Exception {
	}	
}

它们两个非常相似,区别就在于ApplicationRunner的参数是spring的参数,CommandLineRunner的参数是命令行参数。如果没有什么特别的要求,用哪个都行。

执行顺序的处理:

无论是销毁还是启动,有时候我们都希望他们能够按照我们想要的顺序执行。这里就需要一个注解了@Order。如下:

@Order(0)
@Component
public class MyCommandLineRunner1 implements CommandLineRunner{...

@Order(1)
@Component
public class MyApplicationRunner1 implements ApplicationRunner{...

@Order(-1)
@Component
public class MyApplicationRunner2 implements ApplicationRunner{...
``
 执行顺序:MyApplicationRunner2 》MyCommandLineRunner1 》MyApplicationRunner1 ,@Order里的值最小是Integer.min,最大是Integr.max,越小顺序越前。同样的,如果有多个销毁的事件,想要顺序也可以添加@Order

## 其他启动事件:
启动事件分为两种,一种是springboot启动过程中监听事件,一种是springboot启动成功后立即执行的事件.我们刚刚讲的是启动成功后执行的。现在我们来讲启动过程中的监听事件,尽管这个你基本用不到,但是可以了解下。启动中共有6个事件如下:
- ApplicationStartingEvent是在一个运行的开始,但任何处理之前被发送,除了听众和初始化的注册。
- ApplicationEnvironmentPreparedEvent当被发送Environment到中已知的上下文中使用,但是在创建上下文之前。
- ApplicationPreparedEvent刷新开始前,刚刚发,但之后的bean定义已经被加载。
- ApplicationStartedEvent上下文已被刷新后发送,但是任何应用程序和命令行亚军都被调用前。
- ApplicationReadyEvent任何应用程序和命令行亚军被呼叫后发送。它表示应用程序已准备好为请求提供服务。
- ApplicationFailedEvent如果在启动时异常发送。

### 怎么使用呢?
写个 ApplicationStartingEvent事件吧
``` java
public class MyApplicationStartingEvent implements ApplicationListener<ApplicationStartingEvent>{

	@Override
	public void onApplicationEvent(ApplicationStartingEvent event) {
		System.out.println("=================启动========");
	}
}

然后在applicationClass里注册即可

@SpringBootApplication
public class App {
	public static void main(String[] args) {
		SpringApplication application = new SpringApplication(App.class);
		application.addListeners(new MyApplicationStartingEvent());
		application.run(args);
	}
}