软件编程
位置:首页>> 软件编程>> java编程>> 详解SpringBoot程序启动时执行初始化代码

详解SpringBoot程序启动时执行初始化代码

作者:stonesingsong  发布时间:2022-05-07 13:36:05 

标签:SpringBoot,程序启动,初始化代码

因项目集成了Redis缓存部分数据,需要在程序启动时将数据加载到Redis中,即初始化数据到Redis。

在SpringBoot项目下,即在容器初始化完毕后执行我们自己的初始化代码。

第一步:创建实现ApplicationListener接口的类


package com.stone;

import com.stone.service.IPermissionService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

/**
* @author Stone Yuan
* @create 2017-12-02 21:54
* @description
*/
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

@Override
 public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
   IPermissionService service = contextRefreshedEvent.getApplicationContext().getBean(IPermissionService.class);
   service.loadUserPermissionIntoRedis();
 }
}

注意:

1、我们自己的初始化代码写在onApplicationEvent里;

2、ContextRefreshedEvent是Spring的ApplicationContextEvent一个实现,在容器初始化完成后调用;

3、以注解的方式注入我们需要的bean,会报空指针异常,因此需要以代码中的方式获取我们要的bean

第二步:在SpringBootApplication中注册我们刚创建的类


package com.stone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class YwythApplication {

public static void main(String[] args) {
   SpringApplication springApplication = new SpringApplication(YwythApplication.class);
   springApplication.addListeners(new ApplicationStartup());
   springApplication.run(args);
 }
}

利用CommandLineRunner、EnvironmentAware在Spring boot启动时执行初始化代码


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
//如果有多个这样的类时,可以通过Order指定执行顺序,数值越小执行优先级越高
@Order(value = 0)
public class InitSystemConfig implements CommandLineRunner, EnvironmentAware {

/*
  * 在服务启动后执行,会在@Bean实例化之后执行,故如果@Bean需要依赖这里的话会出问题
  */
 @Override
 public void run(String... args) {

//这里可以根据数据库返回结果创建一些对象、启动一些线程等

}

/*
  * 在SystemConfigDao实例化之后、@Bean实例化之前执行
  * 常用于读取数据库配置以供其它bean使用
  * environment对象可以获取配置文件的配置,也可以把配置设置到该对象中
  */
 @Override
 public void setEnvironment(Environment environment) {

}
}

来源:https://www.cnblogs.com/stonesingsong/p/7957258.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com