SpringBoot启动时行初始化方法

有时需要在SpringBoot启动时进行一些初始化的操作,有以下几种方法:

1.实现CommandLineRunner接口

在启动类上实现CommandLineRunner接口,重写run方法

package com.zxh;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
@Slf4j
public class GatewayApplication implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }


    @Value("${server.port}")
    private String port;

    @Override
    public void run(String... args) throws Exception {
        log.info("系统初始化中。。。。。");
        log.info("端口号: {}", port);
    }
}

2.使用注解@PostConstruct

新建一个配置类,在要进行初始化的方法上加注解@PostConstruct:

package com.zxh.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;


import javax.annotation.PostConstruct;

/**
 * 系统初始化操作
 */
@Configuration
@Slf4j
public class WebAppConfig {

    @Value("${server.port}")
    private String port;

    @PostConstruct
    public void initRun() {
        log.info("系统初始化中。。。。。");
        log.info("端口号: {}", port);
    }

}

3.使用注解@EventListener

package com.zxh.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;


/**
 * 系统初始化操作
 */
@Configuration
@Slf4j
public class WebAppConfig {

    @Value("${server.port}")
    private String port;


    @EventListener
    public void initRun(ContextRefreshedEvent event) {
        log.info("系统初始化中。。。。。");
        log.info("端口号: {}", port);
    }

}

4.实现ApplicationRunner接口

新建类,实现ApplicationRunner接口重写run方法,并将其交给Spring管理

package com.zxh.test.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class WebApplicationConfig implements ApplicationRunner {

    @Value("${server.port}")
    private String port;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("系统初始化中。。。。。");
        log.info("端口号: {}", port);
    }
}

对比发现,CommandLineRunner和ApplicationRunner都是实现接口,重写其run方法,它们的作用是相同的,但也有一定的区别。主要区别就在于其run方法中的参数,ApplicationRunner中run方法的参数是ApplicationArguments,而CommandLineRunner中run方法的参数是数组,这些参数都是启动SpringBoot程序时传给main()方法的。ApplicationArguments是对main方的参数做了进一步的封装。


上述的几种方法任选一种即可。

posted @ 2021-09-09 11:16  钟小嘿  阅读(422)  评论(0编辑  收藏  举报