在 SpringBoot 工程 启动后, 执行方法的八种方式:
1、实现 CommandLineRunner 接口
@Component
public class StartInit1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("StartInit1: 可以开始处理事情了");
}
}
2、实现 ApplicationRunner 接口
@Component
public class StartInit2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("StartInit2:开始处理事情");
}
}
3、实现 ApplicationListener 接口
/**
* 监听的是 ApplicationStartedEvent 事件,
* 则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之前执行;
*/
@Component
public class StartInit3 implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("StartInit3:开始处理事情");
}
}
/**
* 监听的是 ApplicationReadyEvent 事件,
* 则 ApplicationListener 一定会在 CommandLineRunner 和 ApplicationRunner 之后执行;
*/
@Component
public class StartInit3_2 implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("StartInit3_2: 开始处理事情");
}
}
4、@PostConstruct 注解
@Component
public class StartInit4 {
@PostConstruct
public void init() {
System.out.println("StartInit4:@PostConstruct===============================");
}
}
5、静态代码块
@Component
public class StartInit5 {
static {
System.out.println("StartInit5:开始处理事情");
}
}
�
6、实现 InitializingBean 接口
@Component
public class StartInit6 implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("StartInit6:开始处理事情");
}
}
7、实现ServletContextAware接口setServletContext 方法
@Component
public class StartInit7 implements ServletContextAware {
@Override
public void setServletContext(ServletContext servletContext) {
System.out.println("StartInit7: 开始处理事情");
}
}
8、@EventListener方式
@Component
public class StartInit8 {
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("StartInit8:开始处理事情");
}
}