当前位置: 移动技术网 > IT编程>开发语言>Java > 详解SpringBoot程序启动时执行初始化代码

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

因项目集成了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) {

  }
}

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网