Spring Boot加载Bean自动执行代码块的几种方式

Spring Boot加载Bean自动执行代码块

  • 说明
    • java自身的启动时加载方式
    • Spring启动时加载方式

在Spring Boot加载Bean的时候有时候我们需要执行一些初始化相关的操作,下面的几种方式可以参考试试。
直接上代码

@Component
public class TestPostConstruct {
    static {
        System.out.println("方式1. static block");
    }

    public TestPostConstruct() {
        System.out.println("方式2. constructor function");
    }

    @PostConstruct
    public void init() {
        System.out.println("方式3. PostConstruct 执行初始化方法");
    }
    
}
@Component
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("方式4. 实现ApplicationRunner类执行run方法");
    }
}
@Component
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("方式5. 实现CommandLineRunner类执行run方法");
    }
}

Spring Boot加载Bean自动执行代码块的几种方式_第1张图片

说明

java自身的启动时加载方式

主要包含下面两种方式

  1. static静态代码块,在类加载的时候即自动执行。(对应方式1)
  2. 构造方法,在对象初始化时执行。执行顺序在static静态代码块之后。(对应方式2)

Spring启动时加载方式

  1. @PostConstruct注解
    PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。(对应方式3)

  2. 实现ApplicationRunnerCommandLineRunner类的run方法(对应方式4.5)
    这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。

注:当有多个类实现了CommandLineRunner和ApplicationRunner接口时,可以通过在类上添加、@Order注解来设定运行顺序。这两个的执行顺序是可以互换的。

代码地址

你可能感兴趣的:(spring,boot,bean,启动)