spring cloud系列-03.程序启动时做额外操作

来源:互联网 发布:程序员必备手机应用 编辑:程序博客网 时间:2024/06/05 19:07

最近在项目过程中需要在程序启动时额外加载一些信息,查询了资料之后终于找到了以下途径。
直接上代码:

package com.xxx.biz;import com.alibaba.fastjson.JSONObject;import com.xxx.biz.dao.AppClientMapper;import com.xxx.biz.dao.AppMapper;import com.xxx.biz.entity.App;import com.xxx.biz.entity.AppClient;import com.xxx.biz.service.IAppService;import com.xxx.redis.util.RedisUtil;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.context.config.annotation.RefreshScope;import org.springframework.cloud.netflix.feign.EnableFeignClients;import org.springframework.context.ApplicationListener;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.transaction.annotation.EnableTransactionManagement;import org.springframework.util.StringUtils;import java.util.List;@EnableTransactionManagement@SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@MapperScan("com.xxx.biz.dao")@ComponentScan("com.xxx")public class BizApp implements ApplicationListener<ContextRefreshedEvent>{    public static void main(String[] args){        SpringApplication.run(BizApp .class, args);    }   /**     程序启动时事件,覆盖ApplicationListener onApplicationEvent方法     在event中可以获取AllicationContext,从而可以获取到spring容器管理的bean实例    */    @Override    public void onApplicationEvent(ContextRefreshedEvent event) {        RedisUtil redisUtil=event.getApplicationContext().getBean(RedisUtil.class);        String appClientValue= redisUtil.getStringValue(IAppService.APP_CLIENT_SECRET_LIST);        if(StringUtils.isEmpty(appClientValue)){            AppClientMapper appClientMapper=event.getApplicationContext().getBean(AppClientMapper.class);            List<AppClient> appClientList= appClientMapper.selectAll();            redisUtil.setStringValue(IAppService.APP_CLIENT_SECRET_LIST, JSONObject.toJSONString(appClientList));        }        String appListValue = redisUtil.getStringValue(IAppService.APP_LIST);        if(StringUtils.isEmpty(appListValue)){            AppMapper appMapper=event.getApplicationContext().getBean(AppMapper.class);            List<App> appList = appMapper.selectAll();            redisUtil.setStringValue(IAppService.APP_LIST, JSONObject.toJSONString(appList));        }    }}