使用场景:可以在程序启动时加载一些自定义的监听器之类的,例如Socket服务的监听器,此时如果使用@PostConstract,Socket服务的监听器将阻塞启动程序,导致程序不能正常启动。
方式一:
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* @author zhangzhixi
* @version 1.0
* @description SpringBoot项目加载后执行,演示一:实现 ApplicationListener 接口
* @date 2023-07-17 10:26
*/
@Component
@Slf4j
public class ProjectLoadExecuteDemo1 implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
log.info("SpringBoot项目加载后执行,演示一:实现 ApplicationListener 接口");
}
}
}
方式二:
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* @author zhangzhixi
* @version 1.0
* @description SpringBoot项目加载后执行,演示二:实现 ApplicationRunner 接口
* @date 2023-07-17 10:26
*/
@Component
@Slf4j
public class ProjectLoadExecuteDemo2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("SpringBoot项目加载后执行,演示二:实现 ApplicationRunner 接口");
}
}
方式三:
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author zhangzhixi
* @version 1.0
* @description SpringBoot项目加载后执行,演示三:实现 ApplicationRunner 接口
* @date 2023-07-17 10:26
*/
@Component
@Slf4j
public class ProjectLoadExecuteDemo3 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("SpringBoot项目加载后执行,演示三:实现 CommandLineRunner 接口");
}
}