SpringBoot启动时初始化资源的几种方法

发布于:2021-10-14 09:02:32

SpringBoot提供了多种方法可实现在启动过程中初始化资源

    使用注解@PostConstruct实现InitializingBean接口实现CommandLineRunner接口实现ApplicationRunner接口监听Spring事件ContextRefreshedEvent

以上5个方法的执行顺序为:


Bean初始化-》依赖注入-》@PostConstruct-》InitializingBean接口-》ContextRefreshedEvent-》ApplicationRunner接口-》CommandLineRunner接口


Talk is cheap. Show me the code!


以下代码在同一个Bean实现以上多种初始化方法,并在每个阶段打印日志信息。


package com.makai.initorder;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.annotation.PostConstruct;

/**
* @ClassName InitClass
* @Description TODO
* @Author m00381966
* @Date 2019/9/2 19:42
* @Version 1.0
*/
public class InitClass implements InitializingBean, CommandLineRunner, ApplicationRunner, ApplicationListener {

public InitClass() {
System.out.println("now is doing construct method");
}

//bean初始化后执行
@PostConstruct
public void postConstruct() {
System.out.println("now is doing @PostConstruct");
}

//bean指定initMethod方法,bean初始化后执行
public void initMethod() {
System.out.println("now is doing initMethod");
}

//实现ApplicationRunner,bean初始化后执行
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("now is doing afterPropertiesSet");
}

//实现CommandLineRunner,SpringBoot启动后后执行
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("now is doing run method of ApplicationRunner Interface");
}

//实现CommandLineRunner,SpringBoot启动后后执行
@Override
public void run(String... args) throws Exception {
System.out.println("now is doing run method of CommandLineRunner Interface");
}

//监听SpringBean加载事件,在springboot 初始化完成时执行
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println("now is doing something when catch a contextRefreshedEvent");
}
}

package com.makai.demo;

import com.makai.initorder.InitClass;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.makai"})
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);

}

@Bean(initMethod = "initMethod")
public InitClass initClass(){
return new InitClass();
}
}

启动过程中打印如下,可以验证各个接口的执行顺序。实际应用中按需选择。


相关推荐

最新更新

猜你喜欢