spring boot启动初始化数据

方式1:项目启动时掉用

一.需求是想将我的写一个方法能在项目启动后就运行,sringboot的监听器

二.目前spring boot中支持的事件类型如下

  1. ApplicationFailedEvent:该事件为spring boot启动失败时的操作

  2. ApplicationPreparedEvent:上下文context准备时触发

  3. ApplicationReadyEvent:上下文已经准备完毕的时候触发

  4. ApplicationStartedEvent:spring boot 启动监听类

  5. SpringApplicationEvent:获取SpringApplication

  6. ApplicationEnvironmentPreparedEvent:环境事先准备

三.监听器的使用

第一:首先定义一个自己使用的监听器类并实现ApplicationListener接口。

复制代码
@Componen
public class MessageReceiver implements ApplicationListener<ApplicationReadyEvent> { private Logger logger = LoggerFactory.getLogger(MessageReceiver.class); private UserService userService = null; @Override public void onApplicationEvent(ApplicationReadyEvent event) { ConfigurableApplicationContext applicationContext = event.getApplicationContext();      //解决userService一直为空      userService = applicationContext.getBean(UserService.class);
     System.out.println("name"+userService.getName()); } }
复制代码

第二:通过SpringApplication类中的addListeners方法将自定义的监听器注册进去

复制代码
public class Application {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners(new MessageReceiver());
        application.run(args);
    
    }
}
复制代码

启动项目

 

 

方式2:项目启动后掉用

spring注解@PostConstruct

@PostConstruct注解详解

往往我们在项目启动时需要加载某个方法的时候,可以使用@Component+@PostConstruct方法将一个方法完成初始化操作,@PostConstruct注解的方法会将在依赖注入完成之后被自动调用。该注解在整个Bean初始化中执行的顺序:

@Constructor(构造方法)->@Autowired(依赖注入)->@PostConstruct(注解的方法)

package org.linlinjava.litemall.wx.task;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class PostConstantAnnotationTest {

    @PostConstruct
    public void init(){
        System.out.println("初始化init方法...");
    }
}

项目运行时初始化init()方法成功!

posted @ 2021-12-09 14:10  91程序猿  阅读(372)  评论(0编辑  收藏  举报