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);
    }

}

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

就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
原文地址:https://www.cnblogs.com/zys2019/p/15246202.html