一、java监听机制(麻烦、繁琐,不推荐)
二、SpringBoot监听机制
三、代码实现
1-包的定义
2-listener代码块
-
1-
MyApplicationContextInitializer
MyApplicationContextInitializer代码块
@Component
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("ApplicationContextInitializer...Run");
}
}
-
2-
MyApplicationRunListener
MyApplicationRunListener代码块
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;
import java.time.Duration;
public class MyApplicationRunListener implements SpringApplicationRunListener {
//根据源码写Controller,没有这个是不可以执行下面的代码的
//下面的参数"SpringApplication application, String[] args"查看springboot的源码
public MyApplicationRunListener(SpringApplication application, String[] args) {
}
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
System.out.println("开始。。。");
}
@Override
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
System.out.println("环境。。。");
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("对象开始准备");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("加载ing。。。");
}
@Override
public void started(ConfigurableApplicationContext context, Duration timeTaken) {
this.started(context);
System.out.println("上下文对象加载完成。。。");
}
@Override
public void running(ConfigurableApplicationContext context) {
System.out.println("项目启动完成。。");
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("项目启动失败");
}
}
-
3-
MyApplicationRunner
MyApplicationRunner代码块
@Component
public class MyApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner...Runner");
System.out.println(Arrays.asList(args.getSourceArgs()));
}
}
-
4-
MyCommandLineRunner
MyCommandLineRunner代码块w
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner...Run");
System.out.println(Arrays.asList(args));
}
}