如何在项目启动后执行一段代码?

使用 ApplicationRunner 这个类来对项目启动后做一些初始化的工作
如:项目启动后,连接websorcek
实现ApplicationRunner的run方法, 在项目启动后, 会自动执行run方法中的内容

package com.diting.hb2.fastdevlop.commons.util;

import com.alibaba.fastjson.JSONObject;
import com.diting.hb2.fastdevlop.commons.cache.DatacodeCache;
import com.diting.hb2.fastdevlop.config.MyWebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class JDDRunner implements ApplicationRunner {
    @Autowired
    RestTemplate restTemplate;

//    @Autowired
//    MyWebSocketClient myWebSocketClient;

    private static final Logger logger = LoggerFactory.getLogger(JDDRunner.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(args);
        System.out.println("springboot项目启动后执行如下内容:");
        DatacodeCache obj = (DatacodeCache)SpringUtil.getBean("datacodeCache");
        Map map = obj.initCacheMap();
        System.out.println("-------------------------------初始化系统编码完成-----------------------------------");
        try
        {
            MyWebSocketClient myWebSocketClient = new MyWebSocketClient();
            ResponseEntity<JSONObject> result =  restTemplate.getForEntity("http://xxxxxxxxxxxxxxxxx" , JSONObject.class);
            String str = result.getBody().get("data").toString();
            System.out.println(str);
            logger.info(str);
            String url = "http://xxxxxxxxxxxx" + str;
            myWebSocketClient.createClient(url);
            logger.info("----------------项目启动后连接 ws 成功---------------");
        }
        catch (Exception e)
        {
            logger.info("----------------连接websocker超时---------------");
        }

    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值