SpringBoot启动时执行初始化某些数据(InitializingBean)

业务场景,在项目开发的过程中我们经常会遇到一些数据基本不变,但有可能需要频繁的从网络或者数据库的获取,这时我们就可在项目启动的时候初始化一次就好。

下面我们以发短信时需要加上国家编码为例:

首先我们需求是在项目启动的时候初始化这个数据的话,这个实现需求的话需要实现InitializingBean接口。这样只要项目启动时数据就会初始化。话不多说直接上代码

package com.hongyu.config;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONArray;
import com.hongyu.domain.vo.CountryVo;
import com.hongyu.untils.USDT4HttpUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 初始化国家编码数据
 * @author Administrator
 *
 */
@Slf4j
@Component
public class CountryInitService implements InitializingBean{

	private static ConcurrentHashMap<String, CountryVo> countries = new ConcurrentHashMap<String, CountryVo>();

	/**
	 * 根据国家编码获取数字代码
	 * @param countryCode
	 * @return
	 */
	public String getTelephoneCode(String countryCode) {
		CountryVo countryDto = countries.get( countryCode );
		if (countryDto == null) {
			return null;
		}
		return countryDto.getTelephoneCode();
	}

	/**
	 * 判断国家编码是否存在
	 * @param countryCode
	 * @return
	 */
	public Boolean isEnable(String countryCode) {
		CountryVo countryDto = countries.get( countryCode );
		if (countryDto == null) {
			return false;
		}
		return countryDto.getEnable();
	}
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		initProvince();
		System.out.println(getTelephoneCode("CN"));
	}
	
	/**
	 * 初始化
	 */
	private static void initProvince() {
        String url = "https://citex-default.oss-cn-hongkong.aliyuncs.com/country.json";
        try {
            String res = USDT4HttpUtils.httpGet(url);
            List<CountryVo> list = JSONArray.parseArray(res, CountryVo.class);
            Map<String, CountryVo> map = list.stream().collect( Collectors.toMap( CountryVo::getId, Function.identity()) );
    	    countries.putAll( map ); 
        } catch (Exception e) {
            log.error("执行初始化代码失败", e);
        }
    }

}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值