Commonly used initialization methods for Springboot projects

1. Preface
     In ordinary project development, we often encounter the need for data initialization. For example, after the project is started, we need to read custom configuration information, initialize custom object information, etc. What are the initialization methods in the springboot project? , let’s talk about it today. In order to facilitate the review of friends, various methods have been implemented in the second chapter, and friends who need to use it can use it directly. As for why this can be done, after reading the relevant official documents, a brief explanation will be given. Interested friends can read the third chapter.

2. Springboot project initialization method in practice
1.ApplicationRunner

@Component
public class PersonalApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("spring容器初始化方式:ApplicationRunner");
    }
}

 2.CommandLineRunner

@Component
public class PersonalCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("spring容器初始化方式:CommandLineRunner");
    }
}

3.ApplicationListener listens to the ContextRefreshedEvent event

@Component
public class PersonalContextRefreshedEvent implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("spring容器初始化方式:ApplicationListener<ContextRefreshedEvent>");
    }
}

4.InitializingBean

@Configuration
public class PersonalInitializingBean implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("spring容器初始化方式:PersonalInitializingBean");
    }
}

5.@PostConstruct

@Configuration
public class PersonalInitializingBean implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("spring容器初始化方式:PersonalInitializingBean");
    }
}

6. Static code blocks

@Component
public class PersonalStacticInit {

    static {
        System.out.println("静态代码块执行。。。。。。。。");
    }
}

 

2. Execution sequence of various initialization operations

      The project starts and the console output is as follows:

Insert image description here 

Reference article:

Commonly used initialization methods for springboot projects. How many do you know? _springboot initialization_The firewood seller’s blog-CSDN blog

Guess you like

Origin blog.csdn.net/yyongsheng/article/details/132295734