spring boot初始化完成时(两种方式)执行某种操作

第一种:

实现接口ApplicationListener,并重写public void onApplicationEvent(ApplicationEvent event) {}可以在容器初始话的时候执行这个方法。

事件类型有以下几种:

1、ApplicationContextEvent

是spring内置事件的父抽象类,构造方法传入spring的context容器,同时也有获取spring的context容器的方法。

2、ContextRefreshedEvent

当spring容器初始化或刷新时,会触发此事件。此事件在开发中常用,用于在spring容器启动时,导入自定义的bean实例到spring容器中。

3、ContextStartedEvent

当spring启动时,或者说是context调用start()方法时,会触发此事件。

4、ContextStoppedEvent

当spring停止时,或者说context调用stop()方法时,会触发此事件。

5、ContextClosedEvent

当spring关闭时,或者说context调用close()方法时,会触发此事件。

package com.sinosoft.speech.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
/**
 * spring boot 容器加载完成后执行
 */
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 初始化完成后. 执行一次同步系统参数
        Scheduler scheduler = contextRefreshedEvent.getApplicationContext().getBean(Scheduler.class);
        scheduler.syncSysParam();
    }
}
 

可以在ApplicationStartup中添加类注解@Component,让spring容器管理起来。

或者在springboot启动类中手动添加listeners

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

 

第二种

spring容器加载完自动监听

实现springboot默认的监听接口即可,该方法在spring容器加载完自动监听

package com.sinosoft.speech.util;
 
import com.sinosoft.speech.swing.Main;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
 * spring boot 容器加载后自动监听
 */
@Component
public class MyCommandRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {

         System.setProperty("address", JsonUtils.objectToJson(addressList));
         //System.out.println("开始启动1个页面");
        //try {
        //    Runtime.getRuntime().exec("cmd   /c   start   http://localhost:8080/index");
        //} catch (Exception ex) {
        //    ex.printStackTrace();
        //}
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值